<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Classes extends BaseController {
    public function __construct() {
        parent::__construct();

        // 移动端初始化方法
        $this->wx_init();
        
        // 加载库
        $this->load->model('schoolModel');
        $this->load->model('configModel');
        $this->load->model('contentModel');
        $this->load->model('classesModel');
        $this->load->model('dataModel');
        $this->load->model('wxUserModel');
    }

    /*
    * 班级课表页面
    */
    public function schedule() {
        $this->htmlTitle = '班级课表';
        // 查询参数
        $classId = $this->get('class_id');
        $date = $this->get('date');
        // 选择当天或者整周
        $this->chooseDay = $this->get('choose_day') ? 1 : 0;
        if(empty($date)) {
            // 未设置默认今天
            $date = date('Y-m-d');
        } else {
            // 传递日期到页面
            $this->date = $date;
        }
        // 通过日期获取星期几
        $weekday = date('w', strtotime($date));
        // 获取课表对应的周几week_index,0=>7,其他相同
        if($weekday == 0) {
            $weekday = 7;
        }
        // 星期几
        $this->weekday = $weekday;
        // 当天是否有课表数据
        $this->dayEmpty = true;
        if($classId) {
            // 获取班级信息
            $this->class = $this->classesModel->get_class_info($classId);
        }
        // 任课班级
        $this->teacherClassArr = array();
        if($this->bindUserType == BIND_TYPE_TEACHER) {
            // 教师权限
            $this->teacherClassArr = $this->get_classes_by_teacher_id();
            if(empty($classId) && !empty($this->teacherClassArr)) {
                // 如未筛选某个班级，默认选择第一个班级
                $class = $this->teacherClassArr['0'];
                $classId = $class['id'];
            }
        } else {
            // 学生权限
            $classId = $this->user['class']['id'];
        }
        if($classId) {
            $classInfo = $this->classesModel->get_class_info($classId);
            $this->class = $classInfo;
        }
        // 获取本校全部老师
        $params['schoolId'] = $this->user['school_id'];
        $teacherList = $this->schoolModel->get_teacher_list($params);
        $teacherList = array_value_to_key($teacherList, 'id');
        // 获取本校全部课室
        $roomParams['schoolId'] = $this->user['school_id'];
        $roomList = $this->classesModel->get_classroom_list($roomParams);
        $roomList = array_value_to_key($roomList, 'id');
        // 获取班级课程表
        $schduleThisWeek = $this->classesModel->get_schedule_by_class($classInfo['school_id'], $classInfo['grade_id']);
        if(empty($schduleThisWeek)) {
            // 学校统一作息
            $schduleThisWeek = $this->classesModel->get_schedule_by_class($classInfo['school_id'], 0);
        }
        // echo '<pre>';var_export($schduleThisWeek);exit;
        if(!empty($schduleThisWeek)){
            // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
            $onlyOneSchedule = $this->classesModel->check_is_only_one_schedule($this->class['school_id'], $this->class['campus_id']);
            if($onlyOneSchedule) {
                // 获取课程
                $lessonParams['scheduleId'] = $schduleThisWeek['id'];
            }

            $lessonParams['classId'] = $classId;
            $lessonList = $this->classesModel->get_school_schedule_lesson($lessonParams);
            foreach($lessonList as &$lesson) {
                // 获取教师名称
                // $lesson['teacherName'] = isset($teacherList[$lesson['schedule_teacher']]) ? $teacherList[$lesson['schedule_teacher']]['realname'] : '';
                // 支持多个授课老师
                $scheduleTeacherIdArr = explode(',', $lesson['schedule_teacher']);
                $scheduleTeacherNameArr = array();
                foreach($scheduleTeacherIdArr as $scheduleTeacherId) {
                    if(isset($teacherList[$scheduleTeacherId])) {
                        array_push($scheduleTeacherNameArr, $teacherList[$scheduleTeacherId]['realname']);
                    }
                }
                $lesson['teacherName'] = implode('，', $scheduleTeacherNameArr);

                // 获取教室名称
                $lesson['roomName'] = isset($roomList[$lesson['schedule_room_id']]) ? $roomList[$lesson['schedule_room_id']]['classroom_name'] : '';
                $lesson['schedule_lesson'] = trim($lesson['schedule_lesson']);
                // 课程名长显示成两行
                if($lesson['schedule_lesson'] && 4 < mb_strlen($lesson['schedule_lesson'], 'utf-8')) {
                    $lesson['showTwoLine'] = true;
                } else {
                    $lesson['showTwoLine'] = false;
                }
                // 将课程放入数组
                $schduleThisWeek['lesson'][$lesson['schedule_week_index']. $lesson['schedule_class_index']] = $lesson;
                // 当天是否有课表数据
                if($lesson['schedule_week_index'] == $this->weekday) {
                    // var_export($lesson);exit;
                    $this->dayEmpty = false;
                    if($onlyOneSchedule == false) {
                        // 当天作息
                        $scheduleId = $lesson['schedule_id'];
                    }
                }
            }
            // 一天课程数
            $schduleThisWeek['schedule_number'] = $schduleThisWeek['schedule_morning_number'] + $schduleThisWeek['schedule_afternoon_number'];
            $this->thisWeek = $schduleThisWeek;
            $this->onlyOneSchedule = $onlyOneSchedule;
            if($onlyOneSchedule == false) {
                $this->gradeScheduleInfo = $this->classesModel->get_school_schedule_info($scheduleId);
            }
        }
        // echo '<pre>';
        // var_export($this->thisWeek);
        // exit;

        $this->display(WX_DIR . DIRECTORY_SEPARATOR . "schedule");
    }

    /*
    * 考场安排页面
    */
    public function exam() {
        $this->htmlTitle = '考试列表';
        // 查询参数
        $classId = $this->get('class_id') ? $this->get('class_id') : '';
        $lessonId = $this->get('lesson_id') ? $this->get('lesson_id') : '';
        if($classId) {
            // 获取班级信息
            $this->class = $this->classesModel->get_class_info($classId);
        }
        if($lessonId) {
            // 获取课程信息
            $this->lesson = $this->schoolModel->get_lesson_info($lessonId);
        }
        // 任课班级
        $this->teacherClassArr = array();
        if($this->bindUserType == BIND_TYPE_TEACHER) {
            // 教师权限
            $this->teacherClassArr = $this->get_classes_by_teacher_id();
            if(empty($classId) && !empty($this->teacherClassArr)) {
                // 如未筛选某个班级，默认选择第一个班级
                $class = $this->teacherClassArr['0'];
                $classId = $class['id'];
            }
        } else {
            // 学生权限
            // $classId = $this->user['class']['id'];
            // 只获取本人的考试，不区分班级
            $params['studentId'] = $this->user['id'];
        }
        if($classId) {
            $classInfo = $this->classesModel->get_class_info($classId);
            $this->class = $classInfo;
            // 只获取班牌对应的课室
            $classroomId = $classInfo['classroom_id'];
            $params['locationId'] = $classroomId;
        }
        if($lessonId) {
            // 筛选科目
            $params['lessonId'] = $lessonId;
        }
        // 根据日期排序
        $orderBy = 'day ASC, begin ASC';
        $params['orderBy'] = $orderBy;
        // 获取哪些属性
        $params['field'] = 'ed.id, day, begin, end, timeslot, part_of_day, lesson_id, grade_id, type, exam_id';
        // 考试列表
        $list = $this->dataModel->get_exam_room_detail_list($params);
        foreach ($list as $key => $val) {
            // 添加星期几属性
            $list[$key]['week'] = date_to_week($val['day']);
            // 添加科目名
            $lessonInfo = $this->schoolModel->get_lesson_info($val['lesson_id']);
            $list[$key]['lesson_name'] = $lessonInfo['lesson_name'];
             // 获取考试年级
             $list[$key]['grade_name'] = '';
             if(!empty($val['grade_id'])){
                 $grade = $this->classesModel->get_grade_info($val['grade_id']);
                 $list[$key]['grade_name'] = $grade['grade_name'];
                 unset($list[$key]['grade_id']);
             }
            // 计算考试时长
            $duration = get_duration($val['begin'], $val['end']);
            $list[$key]['duration'] = $duration;
            // timeslot都加1
            $list[$key]['timeslot'] += 1;
        }
        // 设置考试列表数据
        $this->examList = $list;
        // echo '<pre>';var_export($list);exit;
        // 设置考试科目集合
        $this->lessonArr = $this->_get_exam_lessons($classId);
        // 加个全部选项
        array_unshift($this->lessonArr, array(
            'lesson_name' => '全部',
            'id' => '0'
        ));
        
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . "exam");
    }

    /*
    * 考场信息页面
    */
    public function exam_detail($id) {
        $this->htmlTitle = '考场信息';
        $detail = $this->dataModel->get_exam_room_detail_info($id);
        // 获取考试位置
        if(!empty($detail['location_id'])) {
            $classroom = $this->classesModel->get_classroom_info($detail['location_id'], 1);
            $detail['location'] = isset($classroom['classroom_name']) ? $classroom['classroom_name'] : '';
            // 移除考试位置id
            unset($detail['location_id']);        
        }
        $students = json_decode($detail['students'], true);
        if (null !== $students) {
            foreach($students as $key => $student){
                $studentInfo = $this->schoolModel->get_student_info($student['userID']);
                // 设置默认值
                $students[$key]['name'] = '';
                $students[$key]['class_name'] = '';
                if(empty($studentInfo) || $studentInfo['is_delete'] == 1){
                    continue;
                }
                // 获取学生姓名
                $students[$key]['name'] = $studentInfo['realname'];
                // 获取学生班级名称
                $class = $this->classesModel->get_class_info($studentInfo['class_id']);
                $students[$key]['class_name'] = $class['class_name'];
                // 获取学生账号xid
                $students[$key]['userID'] = $studentInfo['x_student_id'] ? $studentInfo['x_student_id'] : $studentInfo['id'];
            }
        }
        // var_export($students);exit;
        $detail['students'] = $students;

        // 添加科目名
        $lessonInfo = $this->schoolModel->get_lesson_info($detail['lesson_id']);
        $detail['lesson_name'] = $lessonInfo['lesson_name'];
            // 获取考试年级
            $detail['grade_name'] = '';
            if(!empty($detail['grade_id'])){
                $grade = $this->classesModel->get_grade_info($detail['grade_id']);
                $detail['grade_name'] = $grade['grade_name'];
                unset($detail['grade_id']);
            }
        // 计算考试时长
        $duration = get_duration($detail['begin'], $detail['end']);
        $detail['duration'] = $duration;
        // timeslot都加1
        $detail['timeslot'] += 1;
        // 获取监考老师
        $teacherIdArr = explode(',', $detail['inside_teachers']);
        $teacherArr = array();
        foreach($teacherIdArr as $id){
            $teacher = $this->schoolModel->get_teacher_info($id);
            if(!empty($teacher)){
                $teacherArr[] = $teacher['realname'];
            }
        }
        $detail['inside_teachers'] = implode(',', $teacherArr);
        $this->detail = $detail;
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . "exam_detail");
    }

    /*
    * 班级通知页面
    */
    public function notify() {
        $this->htmlTitle = '班级通知';
        // 任课班级
        $this->teacherClassArr = array();
        if($this->bindUserType == BIND_TYPE_TEACHER) {
            // 教师权限
            $this->teacherClassArr = $this->get_classes_by_teacher_id();
        }
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . "notify");
    }

    // 获取通知列表
    public function get_notify_list() {
        $pageStart = $this->get('pageStart');
        $pageSize = $this->get('pageSize');
        $this->notifyList  = array();
        $params['isDelete'] = 0;
        $params['pageStart'] = !empty($pageStart) ? $pageStart : 0;
        $params['pageSize'] = !empty($pageSize) ? $pageSize : 5;
        $params['orderByFirst'] = array('order' => 'is_top', 'sort' =>'DESC');
        $params['orderBy'] = array('order' => 'updatetime', 'sort' =>'DESC');
        if($this->bindUserType == BIND_TYPE_STUDENT) {
            // 当前角色为学生
            if(isset($this->user['class'])) {
                $params['classId'] = $this->user['class']['id'];
                $this->notifyList = $this->contentModel->get_notify_list($params);
            }
        } else {
            // 当前角色为教师
            // $teacherClassIdArr = explode(',', $this->user['class_ids']);
            $teacherClassArr = $this->get_classes_by_teacher_id();
            $teacherClassIdArr = array();
            foreach($teacherClassArr as $class) {
                array_push($teacherClassIdArr, $class['id']);
            }
            $params['classIdArr'] = $teacherClassIdArr;
            $this->notifyList = $this->contentModel->get_notify_list($params);
        }
        foreach($this->notifyList as &$notify) {
            // 转换updatetime为格式：2019.10.10
            $notify['updatetimeFormat'] = format_time_to_date($notify['updatetime']);
            // 获取发送用户信息
            $notifyUser = array();
            if($notify['user_id']) {
                $notifyUser = $this->schoolModel->get_school_user_info_realname($notify['user_id']);
            }
            $notify['notifyUser'] = $notifyUser;
            // 获取通知班级
            $notify['classNameStr'] = $this->_get_class_name_str($notify['class_id']);
            // 获取通知班级类型
            $notify['classTypes'] = $this->_get_classes_types($notify['class_id']);
            // 获取通知图片
            $notify['imgArr'] = $this->_get_img_arr($notify['imgs']);
            // 处理富文本
            if($notify['notify_content']) {
                $notify['notify_content'] = strip_tags($notify['notify_content']);
            }
        }
        exit(json('', true, $this->notifyList));
    }

    /*
    * 发布班级通知页面
    */
    public function notify_send() {
        $this->htmlTitle = '发布班级通知';
        // 判断是发布还是编辑
        $this->notify = array();
        if(!empty($this->get('id'))) {
            // 编辑
            $notify = $this->contentModel->get_notify_info($this->get('id'));
            // 获取通知班级名称
            $notify['classNameStr'] = $this->_get_class_name_str($notify['class_id']);
            // 获取通知班级id数组
            $notify['classIdArr'] = explode(',', $notify['class_id']);
            // 获取通知图片
            $notify['imgArr'] = $this->_get_img_arr($notify['imgs']);
            // 判断content是否为富文本
            if($notify['notify_content'] && $notify['notify_content'] != strip_tags($notify['notify_content'])) {
                $notify['isRichText'] = 1;
            } else {
                $notify['isRichText'] = 0;
            }
            $this->notify = $notify;
        }
        // 任课班级
        $this->teacherClassArr = array();
        if($this->bindUserType == BIND_TYPE_TEACHER) {
            $this->teacherClassArr = $this->get_classes_by_teacher_id();
        }
        $classParams['isDelete'] = 0;
        $classParams['schoolId'] = $this->user['school_id'];
        $classParams['getRowNumber'] = 1;
        $classCount = $this->classesModel->get_class_list($classParams);
        if($classCount == count($this->teacherClassArr) || count($this->teacherClassArr) > 8 || $this->user['user_type'] == USER_TYPE_SCHOOL) {
            // 任课班级数大于8或任课班级是全校班级，即可发送模板消息给全校教师
            $this->isAdmin = true;
        } else {
            $this->isAdmin = false;
        }

        // 判断是否是管理员
        $isSchoolAdmin = false;
        if($this->user['user_type'] == USER_TYPE_SCHOOL) {
            $isSchoolAdmin = true;
        } else {
            // 获取学校管理员执教关系
            $this->load->model('staffModel');
            $coachParams['teacherId'] = $this->user['id'];
            $coachParams['coachType'] = COACH_TYPE_SCHOOL_ADMIN;
            $coachParams['schoolId'] = $this->user['school_id'];
            $coachParams['isDelete'] = 0;
            $schoolAdminCoachList = $this->staffModel->get_coach_list($coachParams);
            if($schoolAdminCoachList) {
                $isSchoolAdmin = true;
            }
        }
        $this->isSchoolAdmin = $isSchoolAdmin;

        // 获取jssdk参数
        $this->load->library('wechat');
        $url = substr(BASE_URL, 0 , -1) . $_SERVER['REQUEST_URI'];
        $this->dataJssdk = $this->wechat->jssdk_data($url);

        $this->display(WX_DIR . DIRECTORY_SEPARATOR . "notify_send");
    }

    // 保存通知操作
    public function save_notify_action() {
        $id = $this->post('id');
        $classIds = $this->post('classIds');
        $title = trim($this->post('title'));
        $content = trim($this->post('content'));
        $isUrgent = $this->post('isUrgent');
        $isTop = $this->post('isTop') ? $this->post('isTop') : 0;
        $sendTeacher = $this->post('sendTeacher');
        $endTime = $this->post('endTime') ? $this->post('endTime') : '';
        $topEnddate = $this->post("isTop") == 1 && $this->post('topEnddate') ? $this->post('topEnddate') : '';
        if($endTime) {
            $pattern = '/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/';
            preg_match($pattern, $endTime, $match);
            if($match) {
                $endTime .= ':00';
            }
        }
        $imgArr = $this->post('imgArr');
        $notifyType = $this->post('notify_type');
        $externalLink = trim($this->post('external_link')) ? trim($this->post('external_link')) : '';
        if(empty($classIds)) {
            throw new Exception('发布班级不能为空');
        }
        if(empty($title)) {
            throw new Exception('标题不能为空');
        }
        if($notifyType == NOTIFY_TYPE_TEXT && empty($content)) {
            throw new Exception('内容不能为空');
        }
        if($imgArr) {
            $imgs = implode(',', $imgArr);
        } else {
            $imgs = '';
        }
        // 如果isUrgent为false,则设置urgent_time为空
        if(!$isUrgent) {
            $endTime = '';
        }
        if($notifyType == NOTIFY_TYPE_LINK) {
            if(empty($externalLink)) {
                throw new Exception("请填写外部链接地址");
            }
            if(false === strstr($externalLink, 'http://') && false === strstr($externalLink, 'https://')) {
                throw new Exception("链接地址格式错误");
            }
            $content = '';
            $imgs = '';
        }
        if($classIds == '-1') {
            // 所有班级
            $teacherClassArr = $this->get_classes_by_teacher_id();
            $teacherClassIdArr = array();
            foreach($teacherClassArr as $class) {
                array_push($teacherClassIdArr, $class['id']);
            }
            $classIds = implode(',', $teacherClassIdArr);
        }
        // 通过班级数组获取校区数组
        $campusIds = $this->_get_campus_by_classes($classIds);
        $data = array(
            'school_id' => $this->user['school_id'],
            'campus_id' => $campusIds,
            'is_delete' => 0,
            'user_id' => $this->user['id'],
            'created_by_mob' => 1,
            'updatetime' => date('Y-m-d H:i:s'),
            'class_id' => $classIds,
            'notify_title' => $title,
            'notify_content' => $content,
            'notify_urgent' => $isUrgent,
            'urgent_endtime' => $endTime,
            'imgs' => $imgs,
            'notify_type' => $notifyType,
            'external_link' => $externalLink,
            'send_teacher' => $sendTeacher
        );
        if($isTop !== "-1") {
            $data['is_top'] = $isTop;
            $data['top_enddate'] = $topEnddate;
        }
        // 操作
        $action = '';
        if(empty($id)) {
            $action = 'insert';
            // 插入
            $data['createtime'] = date('Y-m-d H:i:s');
            $this->db->insert(ContentModel::$notifyTable, $data);
            // 获取detail_id
            $id = $this->db->insert_id();
        } else {
            $action = 'update';
            // 更新
            $this->db->update(ContentModel::$notifyTable, $data, array('id' => $id));
        }
  
        // 修改通知不发送模板消息
        if($action == 'insert') {
            // 发送模板消息
            $this->load->library('wechat');
            // $data = array(
            //     'title' => array(
            //         'value' => $title
            //     ),
            //     'is_urgent' => array(
            //         'value' => $isUrgent ? '是' : '否'
            //     ),
            //     'time' => array(
            //         'value' => date('Y-m-d H:i:s')
            //     )
            // );
            // 发布班级，如大于3个，截取前3个班级
            $classNameStr = $this->_get_class_name_str($classIds);
            $arr = explode('、', $classNameStr);
            if(count($arr) > 3) {
                $newArr = array_slice($arr, 0, 3);
                $classNameStr = implode('、', $newArr) . '...';
            }
            $data = array(
               'first' => array(
                            'value' => '您好，收到新的班级通知：'
                        ),
                'keyword1' => array(
                    'value' => $classNameStr
                ),
                'keyword2' => array(
                    'value' => $this->user['realname']
                ),
                'keyword3' => array(
                    'value' => date('Y-m-d H:i:s')
                ),
                // 'keyword4' =>  array(
                //     'value' => $isUrgent ? '紧急' : '非紧急'
                // ),
                'keyword4' =>  array(
                    'value' => $title
                )
            );
            if($notifyType == NOTIFY_TYPE_TEXT) {
                $url = wx_url('classes/notify_detail/') . $id;
            } else {
                // 跳转外部链接
                $url = $externalLink;
            }

            // 获取学生列表
            $stuParams['isDelete'] = 0;
            $stuParams['schoolId'] = $this->user['school_id'];
            $stuParams['classSet'] = $classIds;
            $students = $this->schoolModel->get_student_list($stuParams);
            if($students) {
                $this->load->model('wxUserModel');
                // 截取成100个
                $arr = array_chunk($students, 100);
                foreach($arr as $studentArr) {
                    $processDataArr = array();
                    foreach($studentArr as $student) {
                        array_push($processDataArr, array(
                            'student_id' => $student['id'],
                            'data' => $data 
                        ));
                    }
                    $this->db->insert(WxUserModel::$wxTemplateProcessTable, array(
                        'template_id' => WX_TEMPLATE_NOTIFY,
                        'type' => 'student',
                        'data' => json_encode($processDataArr, JSON_UNESCAPED_UNICODE),
                        'url' => $url,
                        'include_expired' => 1
                    ));
                }
            }
            // // 发送模板消息给任课教师（暂不发送给老师）
            // $this->load->model('staffModel');
            // // 获取班级的任课老师
            // $coachParams['classSet'] = $classIds;
            // $coachList = $this->staffModel->get_coach_list($coachParams);
            // if($coachList) {
            //     $teachers = array();
            //     foreach($coachList as $coach) {
            //         if(!in_array($coach['teacher_id'], $teachers)) {
            //             array_push($teachers, $coach['teacher_id']);
            //         }
            //     }
            //     if($teachers) {
            //         $this->load->model('wxUserModel');
            //         // 截取成100个
            //         $arr = array_chunk($teachers, 100);

            //         foreach($arr as $teacherIdArr) {
            //             $processDataArr = array();
            //             foreach($teacherIdArr as $teacherId) {
            //                 // echo'<pre>';var_export($student);exit;
            //                 array_push($processDataArr, array(
            //                     'student_id' => $teacherId,
            //                     'data' => $data 
            //                 ));
            //             }
            //             $this->db->insert(WxUserModel::$wxTemplateProcessTable, array(
            //                 'template_id' => WX_TEMPLATE_NOTIFY,
            //                 'type' => 'teacher',
            //                 'data' => json_encode($processDataArr, JSON_UNESCAPED_UNICODE),
            //                 'url' => $url
            //             ));
            //         }
            //     }
            // }
        }

        // 如果是紧急通知，需要推送消息到班牌（加上判断紧急通知截止时间）
        $this->load->library('socket');
        if($isUrgent && $endTime > date('Y-m-d H:i:s')) {
            $this->socket->send_urgent_msg($this->user['school_id'], $classIds, $id);
        } else {
            $this->socket->send_notify_msg($this->user['school_id'], $classIds, $id);
        }

        exit(json('发布成功', true));
    }

    // 删除通知操作
    public function delete_notify_action() {
        $id = $this->post('id');
        if(empty($id)) throw new Exception("参数错误");
        if($this->bindUserType != BIND_TYPE_TEACHER) throw new Exception("删除失败，请刷新后重试");
        $data = array(
            'id' => $id,
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->update(ContentModel::$notifyTable, $data, array('id' => $id));
        exit(json('删除成功', true));
    }

    /*
    * 班级通知详情页面
    */
    public function notify_detail($id) {
        $this->htmlTitle = '班级通知详情';
        // if($this->get('user_id') && $this->get('bind_user_type')) {
        //     // 点击模板消息，自动登录用户
        //     $studentInfo = $this->schoolModel->get_student_info($this->get('user_id'));
        //     // session设置登录的user
        //     $wxSession = $this->session->userdata('wx');
        //     if(empty($wxSession)) {
        //         $sessArr = array(
        //             'user' => $studentInfo,
        //             'bind_user_type' => BIND_TYPE_STUDENT
        //         );
        //     } else {
        //         $sessArr = array_merge($this->wxSession, array(
        //             'user' => $studentInfo,
        //             'bind_user_type' => BIND_TYPE_STUDENT
        //         ));
        //     }
        //     $this->session->set_userdata('wx', $sessArr);
        // }
        // 获取通知详情
        $notify = $this->contentModel->get_notify_info($id);
        // 转换updatetime为格式：2019.10.10
        $notify['updatetimeFormat'] = format_time_to_date($notify['updatetime']);
        // 获取发送用户信息
        $notifyUser = array();
        if($notify['user_id']) {
            $notifyUser = $this->schoolModel->get_school_user_info_realname($notify['user_id']);
        }
        $notify['notifyUser'] = $notifyUser;
        // 获取通知班级
        $notify['classNameStr'] = $this->_get_class_name_str($notify['class_id']);
        // 获取通知图片
        $notify['imgArr'] = $this->_get_img_arr_thumb($notify['imgs']);
        if($notify['notify_content']) {
            $notify['notify_content'] = handle_rich_text_img_preview($notify['notify_content']);
        }
        $this->notify = $notify;
        // 获取jssdk参数
        $this->load->library('wechat');
        $url = substr(BASE_URL, 0 , -1) . $_SERVER['REQUEST_URI'];
        $this->dataJssdk = $this->wechat->jssdk_data($url);

        // 东美学校：家长查看，插入已读记录
        if($this->user['school_id'] == 47) {
            if($this->bindUserType == BIND_TYPE_STUDENT) {
                $this->_mark_read(READ_TYPE_NOTIFY, $id, $this->user, $this->bindUserType);
            }
        }
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . "notify_detail");
    }

    /*
    * 校园公告页面
    */
    public function announce() {
        $this->htmlTitle = '校园公告';
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . "announce");
    }

    // 获取公告列表
    public function get_announce_list() {
        $pageStart = $this->get('pageStart');
        $pageSize = $this->get('pageSize');
        $this->announceList  = array();
        $params['isDelete'] = 0;
        $params['pageStart'] = !empty($pageStart) ? $pageStart : 0;
        $params['pageSize'] = !empty($pageSize) ? $pageSize : 5;
        $params['schoolId'] = $this->user['school_id'];
        $this->announceList = $this->contentModel->get_announce_list($params);
        foreach($this->announceList as &$announce) {
            // 获取发送用户信息
            $announceUser = array();
            if($announce['user_id']) {
                $announceUser = $this->schoolModel->get_school_user_info_realname($announce['user_id']);
            }
            $announce['announceUser'] = $announceUser;
            // 转换updatetime为格式：2019.10.10
            $announce['updatetimeFormat'] = format_time_to_date($announce['updatetime']);
            // 处理富文本
            if($announce['announce_content']) {
                $announce['announce_content'] = strip_tags($announce['announce_content']);
            }
        }
        exit(json('', true, $this->announceList));
    }

    /*
    * 校园公告详情页面
    */
    public function announce_detail($id) {
        $this->htmlTitle = '校园公告详情';
        // if($this->get('user_id') && $this->get('bind_user_type')) {
        //     // 点击模板消息，自动登录用户
        //     if($this->get('bind_user_type') == BIND_TYPE_STUDENT) {
        //         $userInfo = $this->schoolModel->get_student_info($this->get('user_id'));
        //     } else {
        //         $userInfo = $this->schoolModel->get_teacher_info($this->get('user_id'));
        //     }
        //     // session设置登录的user
        //     $wxSession = $this->session->userdata('wx');
        //     if(empty($wxSession)) {
        //         $sessArr = array(
        //             'user' => $userInfo,
        //             'bind_user_type' => $this->get('bind_user_type')
        //         );
        //     } else {
        //         $sessArr = array_merge($this->wxSession, array(
        //             'user' => $userInfo,
        //             'bind_user_type' => $this->get('bind_user_type')
        //         ));
        //     }
        //     $this->session->set_userdata('wx', $sessArr);
        // }

        // 获取公告详情
        $announce = $this->contentModel->get_announce_info($id);
        // 获取发送用户信息
        $announceUser = array();
        if($announce['user_id']) {
            $announceUser = $this->schoolModel->get_school_user_info_realname($announce['user_id']);
        }
        $announce['announceUser'] = $announceUser;
        // 转换updatetime为格式：2019.10.10
        $announce['updatetimeFormat'] = format_time_to_date($announce['updatetime']);
        if($announce['announce_content']) {
            $announce['announce_content'] = handle_rich_text_img_preview($announce['announce_content']);
        }
        $this->announce = $announce;
        // 获取jssdk参数
        $this->load->library('wechat');
        $url = substr(BASE_URL, 0 , -1) . $_SERVER['REQUEST_URI'];
        $this->dataJssdk = $this->wechat->jssdk_data($url);
        // 东美学校：家长查看，插入已读记录
        if($this->user['school_id'] == 47) {
            if($this->bindUserType == BIND_TYPE_STUDENT) {
                $this->_mark_read(READ_TYPE_ANNOUNCE, $id, $this->user, $this->bindUserType);
            }
        }
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . "announce_detail");
    }
    
    /*
    * 发布班级通知页面
    */
    public function announce_send() {
        $this->htmlTitle = '发布校园公告';
        // 判断是发布还是编辑
        $this->announce = array();
        if(!empty($this->get('id'))) {
            // 编辑
            $announce = $this->contentModel->get_announce_info($this->get('id'));
            // 判断content是否为富文本
            if($announce['announce_content'] && $announce['announce_content'] != strip_tags($announce['announce_content'])) {
                $announce['isRichText'] = 1;
            } else {
                $announce['isRichText'] = 0;
            }
            $this->announce = $announce;
        }
       

        $this->display(WX_DIR . DIRECTORY_SEPARATOR . "announce_send");
    }

    // 保存公告操作
    public function save_announce_action() {
        $announceId = $this->post("id");
        $announceTitle = $this->post("title");
        $announceContent = $this->post("content", false);
        $announceType = $this->post('announce_type');
        $externalLink = trim($this->post('external_link'));
        $isTop = $this->post('isTop') ? 1 : 0;
        $topEnddate = $this->post("isTop") == 1 && $this->post('topEnddate') ? $this->post('topEnddate') : '';
        // 参数检查
        if(!$announceTitle) throw new Exception("请填写校园公告标题");


        if($announceType == ANNOUNCE_TYPE_LINK) {
            if(empty($externalLink)) {
                throw new Exception("请填写外部链接地址");
            }
            if(false === strstr($externalLink, 'http://') && false === strstr($externalLink, 'https://')) {
                throw new Exception("链接地址格式错误");
            }
            $notifyContent = '';
        } else {
            if(!$announceContent) throw new Exception("请填写校园公告内容");
            $externalLink = '';
        }

        // 提示信息
        $msg = $announceId ? '修改校园公告成功' : '发布校园公告成功';
        // 入库
        $data['announce_title'] = $announceTitle;
        $data['announce_content'] = $announceContent;
        $data['announce_type'] = $announceType;
        $data['external_link'] = $externalLink;
        $data['updatetime'] = date("Y-m-d H:i:s");
        $data['is_top'] = $isTop;
        $data['top_enddate'] = $topEnddate;
        // 操作
        $action = '';
        if($announceId) {
            $action = 'update';
            $this->db->update(ContentModel::$announceTable, $data, "id='{$announceId}'");
        } else {
            $action = 'insert';
            $data['school_id'] = $this->user['school_id'];
            // 默认校区
            $campusParams['schoolId'] = $this->user['school_id'];
            $campusParams['isDelete'] = 0;
            $campusList = $this->schoolModel->get_campus_list($campusParams);
            $data['campus_id'] = $campusList[0]['id'];
            $data['user_id'] = $this->user['id'];
            $data['createtime'] = $data['updatetime'];
            $this->db->insert(ContentModel::$announceTable, $data);

            $announceId = $this->db->insert_id();
        }

        // 修改不发送模板消息
        if($action == 'insert') {
            // 获取学校信息
            $schoolInfo = $this->schoolModel->get_school_info($this->user['school_id']);
            $data = array(
               'first' => array(
                            'value' => '您好，收到新的校园公告：'
                        ),
                'keyword1' => array(
                    'value' => $schoolInfo['school_name']
                ),
                'keyword2' => array(
                    'value' => $this->user['realname'] ? $this->user['realname'] : $this->user['username']
                ),
                'keyword3' => array(
                    'value' => date("Y-m-d H:i:s")
                ),
                'keyword4' => array(
                    'value' => $announceTitle
                ),
            );
            if($announceType == ANNOUNCE_TYPE_TEXT) {
                $url =wx_url('classes/announce_detail/') . $announceId;
            } else {
                // 跳转外部链接
                $url = $externalLink;
            }
            // 后台进程
            $this->load->model('wxUserModel');
            // 发送全校学生
            $params['isDelete'] = 0;
            $params['schoolId'] = $this->user['school_id'];
            $params['field'] = 'id';
            $students = $this->schoolModel->get_student_list($params);
            if($students) {
                $this->load->model('wxUserModel');
                // 截取成100个
                $arr = array_chunk($students, 100);
                // echo'<pre>';var_export($arr);exit;
                foreach($arr as $studentArr) {
                    $processDataArr = array();
                    foreach($studentArr as $student) {
                        // echo'<pre>';var_export($student);exit;
                        array_push($processDataArr, array(
                            'student_id' => $student['id'],
                            'data' => $data 
                        ));
                    }
                    $this->db->insert(WxUserModel::$wxTemplateProcessTable, array(
                        'template_id' => WX_TEMPLATE_ANNOUNCE,
                        'type' => 'student',
                        'data' => json_encode($processDataArr, JSON_UNESCAPED_UNICODE),
                        'url' => $url
                    ));
                }
            }
            // 发送全校教师
            $params['isDelete'] = 0;
            $params['schoolId'] = $this->user['school_id'];
            $params['field'] = 'id';
            $teachers = $this->schoolModel->get_teacher_list($params);
            if($teachers) {
                $this->load->model('wxUserModel');
                // 截取成100个
                $arr = array_chunk($teachers, 100);
                // echo'<pre>';var_export($arr);exit;
                foreach($arr as $teacherArr) {
                    $processDataArr = array();
                    foreach($teacherArr as $teacher) {
                        // echo'<pre>';var_export($student);exit;
                        array_push($processDataArr, array(
                            'student_id' => $teacher['id'],
                            'data' => $data 
                        ));
                    }
                    $this->db->insert(WxUserModel::$wxTemplateProcessTable, array(
                        'template_id' => WX_TEMPLATE_ANNOUNCE,
                        'type' => 'teacher',
                        'data' => json_encode($processDataArr, JSON_UNESCAPED_UNICODE),
                        'url' => $url
                    ));
                }
            }
        }

        // 发送socket
        $classParams['schoolId'] = $this->user['school_id'];
        $classParams['isDelete'] = 0;
        // 获取全校班级id
        $classArr = $this->classesModel->get_class_list($classParams);
        if($classArr) {
            $classIdArr = array();
            foreach($classArr as $class) {
                array_push($classIdArr, $class['id']);
            }
            $classIdSet = implode(',', $classIdArr);
            $this->load->library('socket');
            $this->socket->send_announce_msg($this->user['school_id'], $classIdSet, $announceId);
        }

        // 返回值
        exit(json($msg, true));
    }

    // 删除公告操作
    public function delete_announce_action() {
        $id = $this->post('id');
        if(empty($id)) throw new Exception("参数错误");
        if($this->bindUserType != BIND_TYPE_TEACHER) throw new Exception("删除失败，请刷新后重试");
        $data = array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->update(ContentModel::$announceTable, $data, array('id' => $id));
        exit(json('删除成功', true));
    }

    /*
    * 班级动态页面
    */
    public function news() {
        $this->htmlTitle = '班级动态';
        // 任课班级
        $this->teacherClassArr = array();
        if($this->bindUserType == BIND_TYPE_TEACHER) {
            // 教师权限
            $this->teacherClassArr = $this->get_classes_by_teacher_id();
        }
        $schoolInfo = $this->schoolModel->get_school_info($this->user['school_id']);
        $this->allowParentSendNews = $schoolInfo['allow_parent_send_news'];
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . "news");
    }

    // 获取动态列表
    public function get_news_list() {
        // 包含家长发布的
        $params['includeSendByTeacher'] = 1;

        $pageStart = $this->get('pageStart');
        $pageSize = $this->get('pageSize');
        $this->newsList  = array();
        $params['isDelete'] = 0;
        $params['pageStart'] = !empty($pageStart) ? $pageStart : 0;
        $params['pageSize'] = !empty($pageSize) ? $pageSize : 5;
        if($this->bindUserType == BIND_TYPE_STUDENT) {
            // 当前角色为学生
            $params['isCron'] = 0;
            if(isset($this->user['class'])) {
                $params['classId'] = $this->user['class']['id'];
                $this->newsList = $this->contentModel->get_news_list($params);
            }
        } else {
            // 当前角色为教师
            // $teacherClassIdArr = explode(',', $this->user['class_ids']);
            $teacherClassArr = $this->get_classes_by_teacher_id();
            $teacherClassIdArr = array();
            foreach($teacherClassArr as $class) {
                array_push($teacherClassIdArr, $class['id']);
            }
            $params['classIdArr'] = $teacherClassIdArr;
            $this->newsList = $this->contentModel->get_news_list($params);
        }
        foreach($this->newsList as &$news) {
            // 转换updatetime为格式：2019.10.10 10:10
            $news['updatetimeFormat'] = format_time_to_minute($news['updatetime']);
            // 获取发送用户信息
            $newsUser = array();
            if($news['user_id']) {
                if($news['send_by_parent'] == 0) {
                    $newsUser = $this->schoolModel->get_school_user_info_realname($news['user_id']);
                } else {
                    // 家长发送
                    $newsUser = $this->schoolModel->get_student_info($news['user_id']);
                }
            }
            $news['newsUser'] = $newsUser;

            // 获取动态班级
            $news['classNameStr'] = $this->_get_class_name_str($news['class_id']);
            // 获取通知班级类型
            $news['classTypes'] = $this->_get_classes_types($news['class_id']);
            // 获取动态图片
            $news['imgArr'] = $this->_get_img_arr($news['imgs']);
            // 处理富文本
            if($news['news_content']) {
                $news['news_content'] = strip_tags($news['news_content']);
            }
        }
        if($this->bindUserType == BIND_TYPE_TEACHER) {
            foreach($this->newsList as $key => $item) {
                // 待发布动态仅对发布人和班主任可见
                 if($item['is_cron'] == 1) {
                     if($item['user_id'] == $this->user['id']) {
                         continue;
                     }
                     $classIds = $item['class_id'];
                     $classIdArr = explode(',', $classIds);
     
                     // 获取班主任对应的班级列表
                     $coachParams['teacherId'] = $this->user['id'];
                     $coachParams['coachType'] = COACH_TYPE_MASTER; 
                     $this->load->model('staffModel');
                     $coachList = $this->staffModel->get_coach_list($coachParams);
                     $isMaster = 0;
                     foreach($coachList as $coach) {
                         $idArr = explode(',', $coach['class_ids']);
                         foreach($idArr as $id) {
                            if(in_array($id, $classIdArr)) {
                                $isMaster = 1;
                            }
                         }
                     }
                     if($isMaster) {
                         continue; 
                     }
                     // 过滤动态
                     unset($this->newsList[$key]);
                 }
             }
        }

        exit(json('', true, $this->newsList));
    }

    /*
    * 发布动态动态页面
    */
    public function news_send() {
        $this->htmlTitle = '发布班级动态';
        // 判断是发布还是编辑
        $this->news = array();
        if(!empty($this->get('id'))) {
            // 编辑
            $news = $this->contentModel->get_news_info($this->get('id'));
            // 获取动态班级名称
            $news['classNameStr'] = $this->_get_class_name_str($news['class_id']);
            // 获取动态班级id数组
            $news['classIdArr'] = explode(',', $news['class_id']);
            // 获取动态图片
            $news['imgArr'] = $this->_get_img_arr($news['imgs']);
            if(trim($news['audios'])) {
                // 获取音频时长
                $news['audioArr'] = json_decode($news['audios'], true);
                require_once('vendor/autoload.php');
                // 初始化又拍云接口
                $config = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
                $upyun = new Upyun\Upyun($config);
                foreach($news['audioArr'] as $key => $audio) {
                    $upyunLink = str_replace(UP_URL, '', $audio['link']);
                    $upyunInfo = $upyun->avMeta($upyunLink);
                    if(isset($upyunInfo['format']) && isset($upyunInfo['format']['duration'])) {
                        $duration = $upyunInfo['format']['duration'];
                        // 向下取整
                        $duration = floor($duration);
                        // 秒数转换为分秒格式02:01
                        $news['audioArr'][$key]['duration'] = handle_audio_duration($duration);
                    } else {
                        // 去掉该音频
                        unset($news['audioArr'][$key]);
                    }
                    // var_export(handle_audio_duration($duration));exit;
                }
               
            }
            if(trim($news['videos'])) {
                $news['videoArr'] = json_decode($news['videos'], true);
                require_once('vendor/autoload.php');
                // 初始化又拍云接口
                $config = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
                $upyun = new Upyun\Upyun($config);
                foreach($news['videoArr']  as &$video) {
                    // 判断视频压缩是否完成
                    // 返回false即视频不存在
                    $linkUpyun = str_replace(UP_URL, '', $video['link']);
                    if($upyun->has($linkUpyun)) {
                        // 转码完成
                        $video['href'] = $video['link'];
                    } else {
                        $video['href'] = $video['old_link'];
                    }
                }
            }
            // 判断content是否为富文本
            if($news['news_content'] && $news['news_content'] != strip_tags($news['news_content'])) {
                $news['isRichText'] = 1;
            } else {
                $news['isRichText'] = 0;
            }
            $this->news = $news;
        }
        $teacherClassArr = array();
        if($this->bindUserType == BIND_TYPE_TEACHER) {
            // 任课班级
            if($this->bindUserType == BIND_TYPE_TEACHER) {
                $teacherClassArr = $this->get_classes_by_teacher_id();
            }
        } else {
            // 家长只能发送本班级
            $classInfo = $this->classesModel->get_class_info($this->user['class_id']);
            $teacherClassArr = array($classInfo);
        }
        $this->teacherClassArr = $teacherClassArr;

        // 获取jssdk参数
        $this->load->library('wechat');
        $url = substr(BASE_URL, 0 , -1) . $_SERVER['REQUEST_URI'];
        $this->dataJssdk = $this->wechat->jssdk_data($url);
        // 生成又拍云签名
        require_once('vendor/autoload.php');
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $serviceConfig->setFormApiKey(UP_FORM_API);
        $serviceConfig->getImageUploadParams(UP_FILEPATH, $this->policy, $this->signature);

        $this->display(WX_DIR . DIRECTORY_SEPARATOR . "news_send");
    }
    
    // 保存动态操作
    public function save_news_action() {
        $id = $this->post('id');
        $classIds = $this->post('classIds');
        $title = trim($this->post('title'));
        $content = trim($this->post('content'));
        $imgArr = $this->post('imgArr');
        // $videoLink = $this->post('videoLink') ? $this->post('videoLink') : '';
        // $videoCover = $this->post('videoCover') ? $this->post('videoCover') : '';
        $isCron = $this->post('is_cron') ? $this->post('is_cron') : 0;
        $audios = $this->post('audios') ? json_encode($this->post('audios'), JSON_UNESCAPED_UNICODE) : '';
        $videos = $this->post('video_arr') ? json_encode($this->post('video_arr'), JSON_UNESCAPED_UNICODE) : '';
        if(empty($classIds)) {
            throw new Exception('发布班级不能为空');
        }
        if(empty($title)) {
            throw new Exception('标题不能为空');
        }
        if(empty($content)) {
            throw new Exception('内容不能为空');
        }
        if($imgArr) {
            $imgs = implode(',', $imgArr);
        } else {
            $imgs = '';
        }
        if($isCron) {
            $cronTime = $this->post('crontime');
            if(empty($cronTime)) {
                if(!$cronTime) throw new Exception("请选择定时发布时间");
            }
        } else {
            $cronTime = '';
        }
        if($this->post('video_arr') && 9 < count($this->post('video_arr'))) {
            throw new Exception("最多只能上传9个视频");
        }
        if($classIds == '-1') {
            // 所有班级
            $teacherClassArr = $this->get_classes_by_teacher_id();
            $teacherClassIdArr = array();
            foreach($teacherClassArr as $class) {
                array_push($teacherClassIdArr, $class['id']);
            }
            $classIds = implode(',', $teacherClassIdArr);
        }
        // 通过班级数组获取校区数组
        $campusIds = $this->_get_campus_by_classes($classIds);
        // 是否家长发送
        if($this->bindUserType == BIND_TYPE_STUDENT) {
            $sendByParent = 1;
        } else {
            $sendByParent = 0;
        }
        $data = array(
            'school_id' => $this->user['school_id'],
            'campus_id' => $campusIds,
            'is_delete' => 0,
            'user_id' => $this->user['id'],
            'created_by_mob' => 1,
            'updatetime' => date('Y-m-d H:i:s'),
            'class_id' => $classIds,
            'news_title' => $title,
            'news_content' => $content,
            'imgs' => $imgs,
            'videos' => $videos,
            // 'video_link' => $videoLink,
            // 'video_cover' => $videoCover,
            'is_cron' => $isCron,
            'crontime' => $cronTime,
            'audios' => $audios,
            'send_by_parent' => $sendByParent
        );
        // 操作
        $action = '';
        if(empty($id)) {
            $action = 'insert';
            // 插入
            $data['createtime'] = date('Y-m-d H:i:s');
            $this->db->insert(ContentModel::$newsTable, $data);
            // 获取detail_id
            $id = $this->db->insert_id();
        } else {
            $action = 'update';
            // 更新
            $this->db->update(ContentModel::$newsTable, $data, array('id' => $id));
        }
        // 家长发送不用发送模板消息
        if($this->bindUserType == BIND_TYPE_TEACHER) {
            if(!$isCron) {
                // 推送消息到客户端
                $this->load->library('socket');
                $this->socket->send_news_msg($this->user['school_id'], $classIds, $id);
    
                // 修改不发送模板消息
                if($action == 'insert') {
                    // 发送模板消息
                    $this->load->library('wechat');
                    // 发布班级，如大于3个，截取前3个班级
                    $classNameStr = $this->_get_class_name_str($classIds);
                    $arr = explode('、', $classNameStr);
                    if(count($arr) > 3) {
                        $newArr = array_slice($arr, 0, 3);
                        $classNameStr = implode('、', $newArr) . '...';
                    }
                    $data = array(
                       'first' => array(
                                'value' => '您好，收到新的班级动态：'
                            ),
                        'keyword1' => array(
                            'value' => $classNameStr
                        ),
                        'keyword2' => array(
                            'value' => $this->user['realname']
                        ),
                        'keyword3' => array(
                            'value' => date('Y-m-d H:i:s')
                        ),
                        'keyword4' =>  array(
                            'value' => $title
                        )
                    );
                    $url =wx_url('classes/news_detail/') . $id;
                    // 获取学生列表
                    $stuParams['isDelete'] = 0;
                    $stuParams['schoolId'] = $this->user['school_id'];
                    $stuParams['classSet'] = $classIds;
                    $students = $this->schoolModel->get_student_list($stuParams);
                    if($students) {
                        $this->load->model('wxUserModel');
                        // 截取成100个
                        $arr = array_chunk($students, 100);
                        foreach($arr as $studentArr) {
                            $processDataArr = array();
                            foreach($studentArr as $student) {
                                array_push($processDataArr, array(
                                    'student_id' => $student['id'],
                                    'data' => $data 
                                ));
                            }
                            $this->db->insert(WxUserModel::$wxTemplateProcessTable, array(
                                'template_id' => WX_TEMPLATE_NOTIFY,
                                'type' => 'student',
                                'data' => json_encode($processDataArr, JSON_UNESCAPED_UNICODE),
                                'url' => $url
                            ));
                        }
                    }
                }
            }
        }

        exit(json('发布成功', true));
    }

    // 删除动态操作
    public function delete_news_action() {
        $id = $this->post('id');
        if(empty($id)) throw new Exception("参数错误");
        // if($this->bindUserType != BIND_TYPE_TEACHER) throw new Exception("删除失败，请刷新后重试");
        $data = array(
            'id' => $id,
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->update(ContentModel::$newsTable, $data, array('id' => $id));
        exit(json('删除成功', true));
    }

    /*
    * 班级动态详情页面
    */
    public function news_detail($id) {
        $this->htmlTitle = '班级动态详情';
        
        // if($this->get('user_id') && $this->get('bind_user_type')) {
        //     // 点击模板消息，自动登录用户
        //     $studentInfo = $this->schoolModel->get_student_info($this->get('user_id'));
        //     // session设置登录的user
        //     $wxSession = $this->session->userdata('wx');
        //     if(empty($wxSession)) {
        //         $sessArr = array(
        //             'user' => $studentInfo,
        //             'bind_user_type' => BIND_TYPE_STUDENT
        //         );
        //     } else {
        //         $sessArr = array_merge($this->wxSession, array(
        //             'user' => $studentInfo,
        //             'bind_user_type' => BIND_TYPE_STUDENT
        //         ));
        //     }
        //     $this->session->set_userdata('wx', $sessArr);
        // }

        // 获取动态详情
        $news = $this->contentModel->get_news_info($id);
        // 转换updatetime为格式：2019.10.10
        $news['updatetimeFormat'] = format_time_to_minute($news['updatetime']);
        // 获取发送用户信息
        $newsUser = array();
        if($news['user_id']) {
            if($news['send_by_parent'] == 0) {
                $newsUser = $this->schoolModel->get_school_user_info_realname($news['user_id']);
            } else {
                // 家长发送
                $newsUser = $this->schoolModel->get_student_info($news['user_id']);
            }
        }
        $news['newsUser'] = $newsUser;
        // 获取动态班级
        $news['classNameStr'] = $this->_get_class_name_str($news['class_id']);
        // 获取动态图片
        $news['imgArr'] = $this->_get_img_arr_thumb($news['imgs']);
        // var_export($news['imgArr']);exit;
        if($news['news_content']) {
            $news['news_content'] = handle_rich_text_img_preview($news['news_content']);
        }
        if(trim($news['audios'])) {
            $news['audioArr'] = json_decode($news['audios'], true);
            require_once('vendor/autoload.php');
            // 初始化又拍云接口
            $config = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
            $upyun = new Upyun\Upyun($config);
            foreach($news['audioArr'] as $key => $audio) {
                $upyunLink = str_replace(UP_URL, '', $audio['link']);
                $upyunInfo = $upyun->avMeta($upyunLink);
                if(isset($upyunInfo['format']) && isset($upyunInfo['format']['duration'])) {
                    $duration = $upyunInfo['format']['duration'];
                    // 向下取整
                    $duration = floor($duration);
                    // 秒数转换为分秒格式02:01
                    $news['audioArr'][$key]['duration'] = handle_audio_duration($duration);
                } else {
                    // 去掉该音频
                    unset($news['audioArr'][$key]);
                }
                // var_export(handle_audio_duration($duration));exit;
            }
        }

        if(trim($news['videos'])) {
            $news['videoArr'] = json_decode($news['videos'], true);
            // 判断视频压缩是否完成
            foreach($news['videoArr'] as $key => $video) {
                // 返回false即图片不存在
                if(false == @file_get_contents($video['link'], null, null, -1, 1)) {
                    $news['videoArr'][$key]['link'] =  isset($video['old_link']) ? $video['old_link'] : '';
                }
            }
        }
        $this->news = $news;
        // 获取jssdk参数
        $this->load->library('wechat');
        $url = substr(BASE_URL, 0 , -1) . $_SERVER['REQUEST_URI'];
        $this->dataJssdk = $this->wechat->jssdk_data($url);
        // exit;
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . "news_detail");
    }

    /*
    * 班级作业页面
    */
    public function homework() {
        $this->htmlTitle = '班级作业';
        // 任课班级
        $this->teacherClassArr = array();
        if($this->bindUserType == BIND_TYPE_TEACHER) {
            // 教师权限
            $this->teacherClassArr = $this->get_classes_by_teacher_id();
        }
        // 任课班级排除班主任，班主任不能发布作业，只可查看
        if($this->bindUserType == BIND_TYPE_TEACHER) {
            // 教师权限
            // 作业支持走班
            $this->teacherClassArrExcludeMaster = $this->get_classes_by_teacher_id(true, false);
        }
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . "homework");
    }

    // 获取作业列表
    public function get_homework_list() {
        $pageStart = $this->get('pageStart');
        $pageSize = $this->get('pageSize');
        $homeworkList  = array();
        $params['isDelete'] = 0;
        $params['pageStart'] = !empty($pageStart) ? $pageStart : 0;
        $params['pageSize'] = !empty($pageSize) ? $pageSize : 5;
        if($this->bindUserType == BIND_TYPE_STUDENT) {
            // 当前角色为学生
            // if(isset($this->user['class'])) {
            //     $params['classId'] = $this->user['class']['id'];
            //     $this->homeworkList = $this->contentModel->get_homework_list($params);
            // }
            // 作业支持走班
            $classIdArr = array();
            // 行政班
            $classIdArr[] = $this->user['class_id'];
            // 走班
            $teacherClassIdArr = explode(',', $this->user['teaching_class_id']);
            if($teacherClassIdArr) {
                foreach($teacherClassIdArr as $teacherClassId) {
                    $classIdArr[] = $teacherClassId;
                }
            }
            $params['classIdArr'] = $classIdArr;
            $homeworkList = $this->contentModel->get_homework_list($params);
            // echo '<pre>';var_export($classIdArr);exit;
        } else {
            // 当前角色为教师
            // $teacherClassIdArr = explode(',', $this->user['class_ids']);
            // $teacherClassArr = $this->get_classes_by_teacher_id();
            // 作业支持走班
            $teacherClassArr = $this->get_classes_by_teacher_id(false, false);
            $teacherClassIdArr = array();
            foreach($teacherClassArr as $class) {
                array_push($teacherClassIdArr, $class['id']);
            }
            $params['classIdArr'] = $teacherClassIdArr;
            $homeworkList = $this->contentModel->get_homework_list($params);
        }

        foreach($homeworkList as $key => $homework) {
            // 转换updatetime为格式：2019.10.10
            $homeworkList[$key]['updatetimeFormat'] = format_time_to_date($homework['updatetime']);
            // 获取发送用户信息
            $homeworkUser = array();
            if($homework['user_id']) {
                $homeworkUser = $this->schoolModel->get_school_user_info_realname($homework['user_id']);
            }
            $homeworkList[$key]['homeworkUser'] = $homeworkUser;
            // 获取作业班级
            $homeworkList[$key]['classNameStr'] = $this->_get_class_name_str($homework['class_id']);
            // 获取作业班级类型
            $homeworkList[$key]['classTypes'] = $this->_get_classes_types($homework['class_id']);
            // 处理富文本
            if($homework['homework_content']) {
                $homeworkList[$key]['homework_content'] = strip_tags($homework['homework_content']);
            }
        }
        if($this->bindUserType == BIND_TYPE_STUDENT) {
            // 获取该学生的作业提交列表
            $stuSubmitParams['schoolId'] = $homework['school_id'];
            $stuSubmitParams['campusId'] = $homework['campus_id'];
            $stuSubmitParams['studentId'] = $this->user['id'];
            $stuSubmitParams['isCurrent'] = 1;
            $stuSubmitParams['isDelete'] = 0;
            $studentHomeworkSubmitList = $this->contentModel->get_homework_submit_list($stuSubmitParams);
            // 使用homework_id作为键值
            $studentHomeworkSubmitList = array_value_to_key($studentHomeworkSubmitList, 'homework_id');
            // 当前角色为学生
            foreach($homeworkList as $key => $homework) {
                $hasSubmit = 0;
                $state = 0;
                $isExcellent = 0;
                $stateFormat = '';
                $homeworkSubmitId = 0;
                if(isset($studentHomeworkSubmitList[$homework['id']])) {
                    $hasSubmit = 1;
                    $state = $studentHomeworkSubmitList[$homework['id']]['state'];
                    $isExcellent = $studentHomeworkSubmitList[$homework['id']]['is_excellent'];
                    $stateFormat = format_homework_submit_state($studentHomeworkSubmitList[$homework['id']]['state']);
                    $homeworkSubmitId = $studentHomeworkSubmitList[$homework['id']]['id'];
                }
                $homeworkList[$key]['has_submit'] = $hasSubmit;
                $homeworkList[$key]['submit_state'] =$state;
                $homeworkList[$key]['is_excellent'] = $isExcellent;
                // 获取提交状态
                $homeworkList[$key]['stateFormat'] = $stateFormat;
                // 作业提交id
                $homeworkList[$key]['homeworkSubmitId'] = $homeworkSubmitId;
            }
        } else {
            // 当前角色为教师
            // 获取作业提交列表
            $submitParams['schoolId'] = $this->user['school_id'];
            $submitParams['isCurrent'] = 1;
            $submitParams['isDelete'] = 0;
            $submitList = $this->contentModel->get_homework_submit_list($submitParams);
            $studentCountArr = array();
            foreach($homeworkList as $key => $homework) {
                // 学生提交作业
                if($homework['can_submit'] == 1) {
                    // 同个班级id集合的只获取一次
                    if(isset($studentCountArr[$homework['class_id']])) {
                        $studentCount = $studentCountArr[$homework['class_id']];
                    } else {
                        // 获取发布班级学生
                        $stuParams['schoolId'] = $homework['school_id'];
                        $stuParams['campusId'] = $homework['campus_id'];
                        $stuParams['classORteach'] = $homework['class_id'];
                        $stuParams['isDelete'] = 0;
                        $stuParams['getRowNumber'] = 1;
                        $studentCount = $this->schoolModel->get_student_list($stuParams);
                        $studentCountArr[$homework['class_id']] = $studentCount;
                    }
                    // 获取作业提交列表
                    // $submitParams['schoolId'] = $homework['school_id'];
                    // $submitParams['campusId'] = $homework['campus_id'];
                    // $submitParams['homeworkId'] = $homework['id'];
                    // $submitParams['isCurrent'] = 1;
                    // $submitParams['isDelete'] = 0;
                    // $submitParams['getRowNumber'] = 1;
                    // $submitCount = $this->contentModel->get_homework_submit_list($submitParams);
                    $submitCount = 0;
                    foreach($submitList as $submit) {
                        // 计算提交作业数
                        if($submit['homework_id'] == $homework['id']) {
                            $submitCount ++;
                        }
                    }
                    $homeworkList[$key]['submitArr'] = array(
                        'student_count' => $studentCount,
                        'submit_count' => $submitCount
                    );
                }
            }
        }
        // echo '<pre>';var_export($homeworkList);exit;
        exit(json('', true, $homeworkList));
    }

    /*
    * 发布作业作业页面
    */
    public function homework_send() {
        $this->htmlTitle = '发布班级作业';
        // 判断是发布还是编辑
        $this->homework = array();
        if(!empty($this->get('id'))) {
            // 编辑
            $homework = $this->contentModel->get_homework_info($this->get('id'));
            // 获取作业班级名称
            $homework['classNameStr'] = $this->_get_class_name_str($homework['class_id']);
            // 获取作业班级id数组
            $homework['classIdArr'] = explode(',', $homework['class_id']);
            // 获取作业图片
            $homework['imgArr'] = $this->_get_img_arr($homework['imgs']);
            // 获取作业科目名称
            $lessonName = '';
            if($homework['lesson_id']) {
                $lesson = $this->schoolModel->get_lesson_info($homework['lesson_id']);
                $lessonName = $lesson['lesson_name'];
            }
            $homework['lessonName'] = $lessonName;
            if(trim($homework['file'])) {
                $homework['fileArr'] = json_decode($homework['file'], true);
            }
            // 判断content是否为富文本
            if($homework['homework_content'] && $homework['homework_content'] != strip_tags($homework['homework_content'])) {
                $homework['isRichText'] = 1;
            } else {
                $homework['isRichText'] = 0;
            }
            $this->homework = $homework;
        }
        // 任课班级
        $this->teacherClassArr = array();
        if($this->bindUserType == BIND_TYPE_TEACHER) {
            // 作业支持走班
            $this->teacherClassArr = $this->get_classes_by_teacher_id(true, false);
        }
        // 获取jssdk参数
        $this->load->library('wechat');
        $url = substr(BASE_URL, 0 , -1) . $_SERVER['REQUEST_URI'];
        $this->dataJssdk = $this->wechat->jssdk_data($url);

        // 科目列表
        $lessonParams['schoolId'] = $this->user['school_id'];
        $lessonParams['isDelete'] = 0;
        $lessonArr = $this->schoolModel->get_lesson_list($lessonParams);
        // 使用id作为键值
        $lessonArr = array_value_to_key($lessonArr, 'id');
        // 任课科目
        $this->load->model('staffModel');
        $coachParams['teacherId'] = $this->user['id'];
        $coachParams['coachType'] = COACH_TYPE_TEACHER; 
        $coachList = $this->staffModel->get_coach_list($coachParams);
        $coachSubjectIdArr = array();
        foreach($coachList as $coach) {
            $subjectIds = $coach['subject_ids'];
            $subjectIdArr = explode(',', $subjectIds);
            $coachSubjectIdArr = array_merge($coachSubjectIdArr, $subjectIdArr);
        }
        $coachSubjectIdArr = array_unique($coachSubjectIdArr);
        $coachSubjectArr = array();
        foreach($coachSubjectIdArr as $coachSubjectId) {
            if(isset($lessonArr[$coachSubjectId])) {
                array_push($coachSubjectArr, $lessonArr[$coachSubjectId]);
            }
        }
        $this->lessonArr = $coachSubjectArr;
        // 生成又拍云签名
        require_once('vendor/autoload.php');
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $serviceConfig->setFormApiKey(UP_FORM_API);
        $serviceConfig->getImageUploadParams(UP_FILEPATH, $this->policy, $this->signature);
        
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . "homework_send");
    }

    // 保存作业操作
    public function save_homework_action() {
        $id = $this->post('id');
        $classIds = $this->post('classIds');
        $lessonId = $this->post('lessonId');
        $title = trim($this->post('title'));
        $content = trim($this->post('content'));
        $imgArr = $this->post('imgArr');
        $file = $this->post('file') ? json_encode($this->post('file'), JSON_UNESCAPED_UNICODE) : '';
        $canSubmit = $this->post('can_submit') ? $this->post('can_submit') : 0;
        if(empty($classIds)) {
            throw new Exception('发布班级不能为空');
        }
        if(empty($lessonId)) {
            throw new Exception('科目不能为空');
        }
        if(empty($title)) {
            throw new Exception('标题不能为空');
        }
        // if(empty($content)) {
        //     throw new Exception('内容不能为空');
        // }
        if($imgArr) {
            if(9 < count($imgArr)) {
                throw new Exception("最多只能上传9张图片");
            }
            $imgs = implode(',', $imgArr);
        } else {
            $imgs = '';
        }
        if($this->post('file') && count($this->post('file')) > 9) {
            throw new Exception("最多只能上传9个附件");
        }
        if($classIds == '-1') {
            // 所有班级
            $teacherClassArr = $this->get_classes_by_teacher_id();
            $teacherClassIdArr = array();
            foreach($teacherClassArr as $class) {
                array_push($teacherClassIdArr, $class['id']);
            }
            $classIds = implode(',', $teacherClassIdArr);
        }
        // 通过班级数组获取校区数组
        $campusIds = $this->_get_campus_by_classes($classIds);
        $data = array(
            'school_id' => $this->user['school_id'],
            'campus_id' => $campusIds,
            'is_delete' => 0,
            'user_id' => $this->user['id'],
            'created_by_mob' => 1,
            'updatetime' => date('Y-m-d H:i:s'),
            'class_id' => $classIds,
            'lesson_id' => $lessonId,
            'homework_title' => $title,
            'homework_content' => $content,
            'imgs' => $imgs,
            'file' => $file,
            'can_submit' => $canSubmit
        );
        // 操作
        $action = '';
        if(empty($id)) {
            $action = 'insert';
            // 插入
            $data['createtime'] = date('Y-m-d H:i:s');
            $this->db->insert(ContentModel::$homeworkTable, $data);
            // 获取detail_id
            $id = $this->db->insert_id();
        } else {
            $action = 'update';
            // 更新
            $this->db->update(ContentModel::$homeworkTable, $data, array('id' => $id));
        }

        // 修改不发送模板消息
        if($action == 'insert') {
            // 发送模板消息
            $this->load->library('wechat');
            // 获取科目名称
            $lesson = $this->schoolModel->get_lesson_info($lessonId);
            if($lesson) {
                $lessonName = $lesson['lesson_name'];
            } else {
                $lessonName = '';
            }
            // 发布班级，如大于3个，截取前3个班级
            $classNameStr = $this->_get_class_name_str($classIds);
            $arr = explode('、', $classNameStr);
            if(count($arr) > 3) {
                $newArr = array_slice($arr, 0, 3);
                $classNameStr = implode('、', $newArr) . '...';
            }
            $keyword2 = $title;
            if($lessonName) {
                // $keyword2 = '（' . $lessonName . '）' . $title;
                $keyword2 = $title;
            }
            $data = array(
                'first' => array(
                    'value' => '您好，收到新的' . $lessonName . '作业：'
                ),
                'keyword1' => array(
                    'value' => $classNameStr
                ),
                'keyword2' => array(
                    'value' => $keyword2
                )
            );
            $url =wx_url('classes/homework_detail/') . $id;
            // 获取学生列表
            $stuParams['isDelete'] = 0;
            $stuParams['schoolId'] = $this->user['school_id'];
            $stuParams['classSet'] = $classIds;
            $students = $this->schoolModel->get_student_list($stuParams);
            if($students) {
                $this->load->model('wxUserModel');
                // 截取成100个
                $arr = array_chunk($students, 100);
                foreach($arr as $studentArr) {
                    $processDataArr = array();
                    foreach($studentArr as $student) {
                        array_push($processDataArr, array(
                            'student_id' => $student['id'],
                            'data' => $data 
                        ));
                    }
                    $this->db->insert(WxUserModel::$wxTemplateProcessTable, array(
                        'template_id' => WX_TEMPLATE_HOMEWORK,
                        'type' => 'student',
                        'data' => json_encode($processDataArr, JSON_UNESCAPED_UNICODE),
                        'url' => $url
                    ));
                }
            }
        }

        // 推送消息到客户端
        $this->load->library('socket');
        $this->socket->send_homework_msg($this->user['school_id'], $classIds, $id);

        exit(json('发布成功', true));
    }

    // 删除作业操作
    public function delete_homework_action() {
        $id = $this->post('id');
        if(empty($id)) throw new Exception("参数错误");
        if($this->bindUserType != BIND_TYPE_TEACHER) throw new Exception("删除失败，请刷新后重试");
        $data = array(
            'id' => $id,
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->update(ContentModel::$homeworkTable, $data, array('id' => $id));
        exit(json('删除成功', true));
    }

    /*
    * 班级作业详情页面
    */
    public function homework_detail($id) {
        $this->htmlTitle = '班级作业详情';
        // if($this->get('user_id') && $this->get('bind_user_type')) {
        //     // 点击模板消息，自动登录用户
        //     $studentInfo = $this->schoolModel->get_student_info($this->get('user_id'));
        //     // session设置登录的user
        //     $wxSession = $this->session->userdata('wx');
        //     if(empty($wxSession)) {
        //         $sessArr = array(
        //             'user' => $studentInfo,
        //             'bind_user_type' => BIND_TYPE_STUDENT
        //         );
        //     } else {
        //         $sessArr = array_merge($this->wxSession, array(
        //             'user' => $studentInfo,
        //             'bind_user_type' => BIND_TYPE_STUDENT
        //         ));
        //     }
        //     $this->session->set_userdata('wx', $sessArr);
        // }
        // 获取作业详情
        $homework = $this->contentModel->get_homework_info($id);
        // 转换updatetime为格式：2019.10.10
        $homework['updatetimeFormat'] = format_time_to_date($homework['updatetime']);
        // 获取发送用户信息
        $homeworkUser = array();
        if($homework['user_id']) {
            $homeworkUser = $this->schoolModel->get_school_user_info_realname($homework['user_id']);
        }
        $homework['homeworkUser'] = $homeworkUser;
        // 获取作业班级
        $homework['classNameStr'] = $this->_get_class_name_str($homework['class_id']);
        // 获取作业图片
        $homework['imgArr'] = $this->_get_img_arr_thumb($homework['imgs']);
        // 获取科目
        $lesson = $this->schoolModel->get_lesson_info($homework['lesson_id']);
        if($lesson) {
            $homework['lessonName'] = $lesson['lesson_name'];
        } else {
            $homework['lessonName'] = '';
        }
        if($homework['homework_content']) {
            $homework['homework_content'] = handle_rich_text_img_preview($homework['homework_content']);
        }
        // 附件
        if($homework['file']) {
            $homework['fileArr'] = json_decode($homework['file'], true);
            // office文件支持预览
            foreach($homework['fileArr'] as &$file) {
                if(preg_match("/^.*\.(doc|docx|ppt|pptx|xls|xlsx)$/", $file['link'])) {
                    $file['linkPreview'] = 'https://view.officeapps.live.com/op/view.aspx?src=' . $file['link'];
                } else {
                    $file['linkPreview'] = $file['link'];
                }
                // $file['linkPreview'] = $file['link'];
            }
        }
        $this->homework = $homework;
        // 学生访问，标记作业已读
        if($this->bindUserType == BIND_TYPE_STUDENT) {
            $this->_mark_read(READ_TYPE_HOMEWORK, $id, $this->user, $this->bindUserType);
            // 作业提交
            if($homework['can_submit'] == 1) {
                // 获取该学生的作业提交
                $stuSubmitParams['schoolId'] = $homework['school_id'];
                $stuSubmitParams['campusId'] = $homework['campus_id'];
                $stuSubmitParams['studentId'] = $this->user['id'];
                $stuSubmitParams['homeworkId'] = $id;
                $stuSubmitParams['isCurrent'] = 1;
                $stuSubmitParams['isDelete'] = 0;
                $studentHomeworkSubmitList = $this->contentModel->get_homework_submit_list($stuSubmitParams);
                $submitInfo = array();
                $homeworkSubmitData = array(
                    'homework_id' => $id,
                    'btnTitle' => '',
                    'stateTitle' => '',
                    'stateImgName' => '',
                    'btnUrl' => '',
                    'is_excellent' => 0
                );
                if($studentHomeworkSubmitList) {
                    $submitInfo = $studentHomeworkSubmitList[0];
                    $homeworkSubmitData['submit_id'] = $submitInfo['id'];
                    $homeworkSubmitData['state'] = $submitInfo['state'];
                    if($submitInfo['state'] == HOMEWORK_SUBMIT_STATE_NOT_REVIEW) {
                        // 待批阅
                        $homeworkSubmitData['btnTitle'] = '修改作业';
                        $homeworkSubmitData['stateImgName'] = 'not_review';
                        $homeworkSubmitData['stateTitle'] = '待批阅';
                        $homeworkSubmitData['btnUrl'] = wx_url('homeworksubmit/homework_submit_edit/') . $id . "?homework_submit_id=" . $submitInfo['id']; 
                    } elseif($submitInfo['state'] == HOMEWORK_SUBMIT_STATE_REVIEW) {
                        // 已批阅
                        $homeworkSubmitData['btnTitle'] = '查看作业';
                        $homeworkSubmitData['stateImgName'] = 'review';
                        $homeworkSubmitData['stateTitle'] = '已批阅';
                        $homeworkSubmitData['btnUrl'] = wx_url('homeworksubmit/homework_submit_check/') . $id . "?homework_submit_id=" . $submitInfo['id'];
                        $homeworkSubmitData['is_excellent'] = $submitInfo['is_excellent'];
                    } elseif($submitInfo['state'] == HOMEWORK_SUBMIT_STATE_NOT_REVISE) {
                        // 待订正
                        $homeworkSubmitData['btnTitle'] = '订正作业';
                        $homeworkSubmitData['stateImgName'] = 'not_revise';
                        $homeworkSubmitData['stateTitle'] = '待订正';
                        $homeworkSubmitData['btnUrl'] = wx_url('homeworksubmit/homework_submit_check/') . $id . "?homework_submit_id=" . $submitInfo['id'] . '&is_revise=1';
                    } elseif($submitInfo['state'] == HOMEWORK_SUBMIT_STATE_REVISE) {
                        // 已订正
                        $homeworkSubmitData['btnTitle'] = '修改作业';
                        $homeworkSubmitData['stateImgName'] = 'not_review';
                        $homeworkSubmitData['stateTitle'] = '已订正';
                        $homeworkSubmitData['btnUrl'] = wx_url('homeworksubmit/homework_submit_edit/') . $id . "?homework_submit_id=" . $submitInfo['id'];
                    }
                } else {
                    // 未提交
                    $homeworkSubmitData['btnTitle'] = '提交作业';
                    $homeworkSubmitData['btnUrl'] = wx_url('homeworksubmit/homework_submit_edit/') . $id;
                }
                $this->homeworkSubmitData = $homeworkSubmitData;
            }
        }
        // 获取jssdk参数
        $this->load->library('wechat');
        $url = substr(BASE_URL, 0 , -1) . $_SERVER['REQUEST_URI'];
        $this->dataJssdk = $this->wechat->jssdk_data($url);
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . "homework_detail");
    }

    /*
    * 班级考勤页面
    */
    public function sign() {
        $this->htmlTitle = '班级考勤';
        // 查询参数
        $classId = $this->get('class_id');
        $date = $this->get('date');
        if(empty($date)) {
            // 未设置默认今天
            $date = date('Y-m-d');
        }
        $this->date = $date;

        // 第几节
        $timeslot = $this->get('timeslot');

        if($classId) {
            // 获取班级信息
            $this->class = $this->classesModel->get_class_info($classId);
        }
        // 任课班级
        $this->teacherClassArr = array();
        if($this->bindUserType == BIND_TYPE_TEACHER) {
            // 判断是否学校管理员
            // 获取学校管理员对应的年级列表
            $isSchoolAdmin = false;
            if($this->user['user_type'] == USER_TYPE_SCHOOL) {
                $isSchoolAdmin = true;
            } else {
                $this->load->model('staffModel');
                $coachParams['teacherId'] = $this->user['id'];
                $coachParams['coachType'] = COACH_TYPE_SCHOOL_ADMIN; 
                $schoolAdminCoachList = $this->staffModel->get_coach_list($coachParams);
                if($schoolAdminCoachList) {
                    $isSchoolAdmin = true;
                }
            }
            // 管理员可以查看走班
            if($isSchoolAdmin) {
                // echo'<pre>';var_export($this->user);exit;
                 // 管理员权限
                $this->teacherClassArr = $this->get_classes_by_teacher_id(false, false);
            } else {
                // 教师权限（可以查看走班）
                $this->teacherClassArr = $this->get_classes_by_teacher_id(false, false);
            }
          
            if(empty($classId) && !empty($this->teacherClassArr)) {
                // 如未筛选某个班级，默认选择第一个班级
                $class = $this->teacherClassArr['0'];
                $classId = $class['id'];
            }
        } else {
            // 学生权限
            $classId = $this->user['class']['id'];
        }
        $this->class = $classInfo = $this->classesModel->get_class_info($classId);
        // echo'<pre>';var_export($this->teacherClassArr);exit;

        // 获取之前最近的重新签到课程，包含本节课
        $schduleParams['schoolId'] = $this->user['school_id'];
        $schduleParams['isThisWeek'] = 1;
        $scheduleInfo = $this->classesModel->get_school_schedule_row($schduleParams);

        // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
        $onlyOneSchedule = $this->classesModel->check_is_only_one_schedule($this->class['school_id'], $this->class['campus_id']);
        if(!$onlyOneSchedule) {
            $w = date('w', strtotime($this->date));
            // 转换date('w')获取的值为作息时间的week
            $this->load->helper('schedule');
            $week = transform__to_schedule_week($w);
            $mondayGradeSchedule = $this->classesModel->get_one_daily_grade_schdedule_by_week($this->class['school_id'], $this->class['campus_id'], $this->class['grade_id'], $week);
            if($mondayGradeSchedule) {
                $scheduleInfo = $mondayGradeSchedule;
            }
        }
        // var_export($scheduleInfo);exit;
        $timeArr = json_decode($scheduleInfo['schedule_time_json'], true);

        $classIndex = $this->dataModel->get_class_index($timeArr, $this->date);
        $timeslotArr = array();
 
        // for($i = 1; $i <= $classIndex; $i++) {
        //     $lessonTime = $timeArr[$i - 1];
        //     $lessonBeginTime = $lessonTime['beginTime'];
        //     $lessonEndTime = date('H:i', strtotime($lessonTime['beginTime']) + $lessonTime['duration'] * 60); 

        //     $v = '第' . $i . '节 （' . $lessonBeginTime . '-' . $lessonEndTime . '）';
        //     array_push($timeslotArr, $v);
        // }

        // 支持早读，晚间
        $timeslotPrefixArr = array();
        if($scheduleInfo['schedule_early_morning_number'] > 0) {
            for($i = 0;$i < $scheduleInfo['schedule_early_morning_number'];$i++) {
                $tmpIndex = $i + 1;
                $timeslotPrefixArr[] = '早间' . $tmpIndex;
            }
        }
        $dayScheduleNum = $scheduleInfo['schedule_morning_number'] + $scheduleInfo['schedule_afternoon_number'];
        for($i = 0;$i < $dayScheduleNum;$i++) {
            $tmpIndex = $i + 1;
            $timeslotPrefixArr[] = '第' . $tmpIndex . '节';
        }
        if($scheduleInfo['schedule_night_number'] > 0) {
            for($i = 0;$i < $scheduleInfo['schedule_night_number'];$i++) {
                $tmpIndex = $i + 1;
                $timeslotPrefixArr[] = '晚间' . $tmpIndex;
            }
        }
        // 当天也显示全部节数
        for($i = 1; $i <= count($timeArr); $i++) {
            $lessonTime = $timeArr[$i - 1];
            $lessonBeginTime = $lessonTime['beginTime'];
            $lessonEndTime = date('H:i', strtotime($lessonTime['beginTime']) + $lessonTime['duration'] * 60);

            // 揭阳第二中学，揭阳特殊教育学校：显示考勤时间段，而不是上课时间段
            $schoolInfo = $this->schoolModel->get_school_info($this->user['school_id']);
            if($schoolInfo['id'] == 45 || $schoolInfo['id'] == 28) {
                $lessonBeginTime = date("H:i", strtotime($lessonTime['beginTime']) - ($lessonTime['sign_interval']) * 60);
                $lessonEndTime = $lessonTime['beginTime'];
            }
            if(isset($timeslotPrefixArr[$i - 1])) {
                $prefix = $timeslotPrefixArr[$i - 1];
            } else {
                $prefix = '';
            }
            $v = $prefix . '（' . $lessonBeginTime . '-' . $lessonEndTime . '）';
            array_push($timeslotArr, $v);
        }
        // echo '<pre>';var_export($timeslotPrefixArr);exit;
        if($timeslot) {
            $classIndex = $timeslot;
        }
        $this->timeslotPrefixArr = $timeslotPrefixArr;
        $this->classIndex = $classIndex;
        $this->timeslotArr = $timeslotArr;

        // foreach($dataArr as &$item) {
        //     if($item['sign_id']) {
        //         if($item['state'] == SIGN_STATE_LEAVE) {
        //             // 离校
        //             $item['sign_id'] = 0;
        //         } else {
        //             if($item['schedule_class_index'] < $refreshClassIndex) {
        //                 // 重新签到后还没签
        //                 $item['sign_id'] = 0;
        //             }
        //         }
        //     }
        // }
        // $signData = array();
        // $notSignData = array();
        // foreach($dataArr as $data) {
        //     // 处理温度
        //     $data['temperature'] = handle_temperature($data['temperature']);

        //     if($data['sign_id'] && $data['schedule_class_index'] >= $refreshClassIndex) {
        //         // 已签到
        //         // 判断是否正常签到或迟到补签
        //         if($data['state'] == SIGN_STATE_NORMAL_SUPPLEMENT || $data['state'] == SIGN_STATE_TEACH_SUPPLEMENT) {
        //             $data['signState'] = '<span class="text-danger">迟到补签</span>';

        //             // 获取第几节课的开始签到时间
        //             $beginTime = $this->dataModel->get_lesson_sign_begin_time($timeArr, $refreshClassIndex);
        //             $endTime = $this->dataModel->get_lesson_end_time($timeArr, $this->classIndex);
        //             $beginTime = $this->date . ' ' . $beginTime;
        //             $endTime = $this->date . ' ' . $endTime;
        //             // 判断本节课是否有正常签到过
        //             $signInfo = $this->dataModel->get_student_sign_info_by_time($data['id'], $beginTime, $endTime, true);
        //             if($signInfo) {
        //                 $data['signState'] = '正常签到';
        //                 $data['signTime'] = $signInfo['createtime'];
        //             }
        //             // var_export($data);exit;
        //         } else {
        //             $data['signState'] = '<span class="text-success">正常签到</span>';
        //         }
        //         // 签到时间，去除日期
        //         $data['signTimeExcludeDate'] = explode(' ', $data['signTime'])[1];
        //         array_push($signData, $data);
        //     } else {
        //         // 未签到
        //         array_push($notSignData, $data);
        //     }
        // }
        // $this->signData = $signData;
        // $this->notSignData = $notSignData;
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . "sign");
    }

    // 获取班级某天的考勤数据
    function get_class_date_sign_data() {
        $classId = $this->get('class_id');
        $date = $this->get('date');
        // 第几节
        $timeslot = $this->get('timeslot');
        if(empty($date)) {
            // 未设置默认今天
            $date = date('Y-m-d');
        }

        $classInfo = $this->classesModel->get_class_info($classId);

        // 获取之前最近的重新签到课程，包含本节课
        $schduleParams['schoolId'] = $this->user['school_id'];
        $schduleParams['isThisWeek'] = 1;
        $scheduleInfo = $this->classesModel->get_school_schedule_row($schduleParams);

        // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
        $onlyOneSchedule = $this->classesModel->check_is_only_one_schedule($classInfo['school_id'], $classInfo['campus_id']);
        if(!$onlyOneSchedule) {
            $w = date('w', strtotime($date));
            // 转换date('w')获取的值为作息时间的week
            $this->load->helper('schedule');
            $week = transform__to_schedule_week($w);
            $mondayGradeSchedule = $this->classesModel->get_one_daily_grade_schdedule_by_week($classInfo['school_id'], $classInfo['campus_id'], $classInfo['grade_id'], $week);
            if($mondayGradeSchedule) {
                $scheduleInfo = $mondayGradeSchedule;
            }
        }
        // var_export($scheduleInfo);exit;
        $timeArr = json_decode($scheduleInfo['schedule_time_json'], true);

        // 是否教学班
        $isTeaching = $classInfo['class_type'] == CLASSES_TYPE_TEACHING ? 1 : 0;
         // 获取第几节课的下课时间
        if($timeslot) {
            $lessonEndTime = $this->dataModel->get_lesson_end_time($timeArr, $timeslot);
            // 获取考勤数据
            $dataArr = $this->dataModel->get_sign_data($classInfo, $date, $isTeaching, 0, $lessonEndTime);
            $refreshClassIndex = $this->dataModel->get_refresh_class_index($timeArr, $date, $timeslot);
        } else {
            // 获取考勤数据
            $dataArr = $this->dataModel->get_sign_data($classInfo, $date, $isTeaching);
            // 判断当前时间属于第几节课
            // 之前日期的考勤按最后一节情况
            $refreshClassIndex = $this->dataModel->get_refresh_class_index($timeArr, $date);
        }

    // exit(json('', true, $dataArr));

        $classIndex = $this->dataModel->get_class_index($timeArr, $date);
        $timeslotArr = array();
 
        for($i = 1; $i <= $classIndex; $i++) {
            $lessonTime = $timeArr[$i - 1];
            $lessonBeginTime = $lessonTime['beginTime'];
            $lessonEndTime = date('H:i', strtotime($lessonTime['beginTime']) + $lessonTime['duration'] * 60); 

            $v = '第' . $i . '节 （' . $lessonBeginTime . '-' . $lessonEndTime . '）';
            array_push($timeslotArr, $v);
        }
        if($timeslot) {
            $classIndex = $timeslot;
        }

        foreach($dataArr as &$item) {
            if($item['sign_id']) {
                if($item['state'] == SIGN_STATE_LEAVE) {
                    // 离校
                    $item['sign_id'] = 0;
                } else {
                    if($item['schedule_class_index'] < $refreshClassIndex) {
                        // 重新签到后还没签
                        $item['sign_id'] = 0;
                    }
                }
            }
        }
        $signData = array();
        $notSignData = array();
        foreach($dataArr as $data) {
            // 处理温度
            $data['temperature'] = handle_temperature($data['temperature']);

            if($data['sign_id'] && $data['schedule_class_index'] >= $refreshClassIndex) {
                // 已签到
                // 判断是否正常签到或迟到补签
                if($data['state'] == SIGN_STATE_NORMAL_SUPPLEMENT || $data['state'] == SIGN_STATE_TEACH_SUPPLEMENT) {
                    $data['signState'] = '<span class="text-danger">迟到补签</span>';

                    // 获取第几节课的开始签到时间
                    $beginTime = $this->dataModel->get_lesson_sign_begin_time($timeArr, $refreshClassIndex);
                    $endTime = $this->dataModel->get_lesson_end_time($timeArr, $classIndex);
                    $beginTime = $date . ' ' . $beginTime;
                    $endTime = $date . ' ' . $endTime;
                    // 判断本节课是否有正常签到过
                    $signInfo = $this->dataModel->get_student_sign_info_by_time($data['id'], $beginTime, $endTime, true);
                    if($signInfo) {
                        $data['signState'] = '正常签到';
                        $data['signTime'] = $signInfo['createtime'];
                    }
                    // var_export($data);exit;
                } else {
                    $data['signState'] = '<span class="text-success">正常签到</span>';
                }
                // 签到时间，去除日期
                $data['signTimeExcludeDate'] = explode(' ', $data['signTime'])[1];
                array_push($signData, $data);
            } else {
                // 未签到
                array_push($notSignData, $data);
            }
        }

        $resArr = array(
            'sign_data' => $signData,
            'not_sign_data' => $notSignData
        );

        exit(json('', true, $resArr));
    }

    /*
     * 我的考勤页面
    */
    public function my_sign($studentId = 0) {

        // 默认本周日期
        $thisWeekDateArr = get_this_week_date();
        $dateArr['begin_date'] = $thisWeekDateArr[0];
        $dateArr['end_date'] = $thisWeekDateArr[count($thisWeekDateArr) - 1];
        $this->dateArr = $dateArr;


        if($studentId) {
            $studentInfo = $this->schoolModel->get_student_info($studentId);
            if($studentInfo) {
                $htmlTitle = '考勤查询 -' . $studentInfo['realname'];
            }
        } else {
            $studentId = $this->user['id'];
            $studentInfo = $this->schoolModel->get_student_info($studentId);
            $htmlTitle = '我的考勤';
        }
        $this->htmlTitle = $htmlTitle;

        // 第几节
        $timeslot = $this->get('timeslot');
        // 获取之前最近的重新签到课程，包含本节课
        $schduleParams['schoolId'] = $this->user['school_id'];
        $schduleParams['isThisWeek'] = 1;
        $scheduleInfo = $this->classesModel->get_school_schedule_row($schduleParams);

        // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
        $onlyOneSchedule = $this->classesModel->check_is_only_one_schedule($studentInfo['school_id'], $studentInfo['campus_id']);
        if(!$onlyOneSchedule) {
            $classInfo = $this->classesModel->get_class_info($studentInfo['class_id']);
            $mondayGradeSchedule = $this->classesModel->get_one_daily_grade_schdedule_by_week($studentInfo['school_id'], $studentInfo['campus_id'], $classInfo['grade_id'], 1);
            if($mondayGradeSchedule) {
                $scheduleInfo = $mondayGradeSchedule;
            }
        }
        // 支持早读，晚间
        $timeslotPrefixArr = array();
        if($scheduleInfo['schedule_early_morning_number'] > 0) {
            for($i = 0;$i < $scheduleInfo['schedule_early_morning_number'];$i++) {
                $tmpIndex = $i + 1;
                $timeslotPrefixArr[] = '早间' . $tmpIndex;
            }
        }
        $dayScheduleNum = $scheduleInfo['schedule_morning_number'] + $scheduleInfo['schedule_afternoon_number'];
        for($i = 0;$i < $dayScheduleNum;$i++) {
            $tmpIndex = $i + 1;
            $timeslotPrefixArr[] = '第' . $tmpIndex . '节';
        }
        if($scheduleInfo['schedule_night_number'] > 0) {
            for($i = 0;$i < $scheduleInfo['schedule_night_number'];$i++) {
                $tmpIndex = $i + 1;
                $timeslotPrefixArr[] = '晚间' . $tmpIndex;
            }
        }
        // var_export($scheduleInfo);exit;
        $timeArr = json_decode($scheduleInfo['schedule_time_json'], true);
        $timeslotArr = array();
 
        // 返回所有节数
        for($i = 1; $i <= count($timeArr); $i++) {
            $lessonTime = $timeArr[$i - 1];
            $lessonBeginTime = $lessonTime['beginTime'];
            $lessonEndTime = date('H:i', strtotime($lessonTime['beginTime']) + $lessonTime['duration'] * 60); 
            // 揭阳第二中学，揭阳特殊教育学校：显示考勤时间段，而不是上课时间段
            $schoolInfo = $this->schoolModel->get_school_info($this->user['school_id']);
            if($schoolInfo['id'] == 45 || $schoolInfo['id'] == 28) {
                $lessonBeginTime = date("H:i", strtotime($lessonTime['beginTime']) - ($lessonTime['sign_interval']) * 60);
                $lessonEndTime = $lessonTime['beginTime'];
            }
            if(isset($timeslotPrefixArr[$i - 1])) {
                $prefix = $timeslotPrefixArr[$i - 1];
            } else {
                $prefix = '';
            }
            $v = $prefix . '（' . $lessonBeginTime . '-' . $lessonEndTime . '）';
            array_push($timeslotArr, $v);
        }

        // 第几节
        $timeslot = $this->get('timeslot') ? $this->get('timeslot') : 0;
        // 默认获取所有节数
        $this->classIndex = $timeslot;
        if($timeslot == 0) {
            $this->classIndexStr = '全部';
        } else {
            $this->classIndexStr = '第' . $timeslot . '节';
        }

        $this->timeslotArr = $timeslotArr;
        // 教师查看学生考勤，传学生id
        $this->studentId = $studentId;

        // var_export($this->classIndex);exit;
        if($this->classIndex == 0) {
            $timeslotPrefix = '全部';
        } else {
            $timeslotPrefix = $timeslotPrefixArr[$this->classIndex - 1];
        }
        $this->timeslotPrefix = $timeslotPrefix;
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'my_sign');
    }

    // 已废弃
    public function my_sign_old($studentId = 0) {
        if($studentId) {
            $studentInfo = $this->schoolModel->get_student_info($studentId);
            if($studentInfo) {
                $htmlTitle = '考勤查询-' . $studentInfo['realname'];
            }
        } else {
            $htmlTitle = '我的考勤';
        }
        $this->htmlTitle = $htmlTitle;

        // 未设置默认今天
        $date = date('Y-m-d');

        // 第几节
        $timeslot = $this->get('timeslot');
        // 获取之前最近的重新签到课程，包含本节课
        $schduleParams['schoolId'] = $this->user['school_id'];
        $schduleParams['isThisWeek'] = 1;
        $scheduleInfo = $this->classesModel->get_school_schedule_row($schduleParams);

        // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
        $onlyOneSchedule = $this->classesModel->check_is_only_one_schedule($this->user['class']['school_id'], $this->user['class']['campus_id']);
        if(!$onlyOneSchedule) {
            $mondayGradeSchedule = $this->classesModel->get_one_daily_grade_schdedule_by_week($this->user['class']['school_id'], $this->user['class']['campus_id'], $this->user['class']['grade_id'], 1);
            if($mondayGradeSchedule) {
                $scheduleInfo = $mondayGradeSchedule;
            }
        }

        // var_export($scheduleInfo);exit;
        $timeArr = json_decode($scheduleInfo['schedule_time_json'], true);

        // // 获取第几节课的下课时间
        // if($timeslot) {
        //     $lessonEndTime = $this->dataModel->get_lesson_end_time($timeArr, $timeslot);
        //     // 获取考勤数据
        //     $dataArr = $this->dataModel->get_sign_data($classInfo, $this->date, false, 0, $lessonEndTime);
        //     $refreshClassIndex = $this->dataModel->get_refresh_class_index($timeArr, $this->date, $timeslot);
        // } else {
        //     // 获取考勤数据
        //     $dataArr = $this->dataModel->get_sign_data($classInfo, $this->date);
        //     // 判断当前时间属于第几节课
        //     // 之前日期的考勤按最后一节情况
        //     $refreshClassIndex = $this->dataModel->get_refresh_class_index($timeArr, $this->date);
        // }

        $classIndex = $this->dataModel->get_class_index($timeArr, $date);
        $timeslotArr = array();
 
        // 返回所有节数
        for($i = 1; $i <= count($timeArr); $i++) {
            $lessonTime = $timeArr[$i - 1];
            $lessonBeginTime = $lessonTime['beginTime'];
            $lessonEndTime = date('H:i', strtotime($lessonTime['beginTime']) + $lessonTime['duration'] * 60); 

            $v = '第' . $i . '节 （' . $lessonBeginTime . '-' . $lessonEndTime . '）';
            array_push($timeslotArr, $v);
        }
        if($timeslot) {
            $classIndex = $timeslot;
        }
        $this->classIndex = $classIndex;
        $this->timeslotArr = $timeslotArr;
        // 教师查看学生考勤，传学生id
        $this->studentId = $studentId;

        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'my_sign');
    }

    // 获取我的考勤
    public function get_user_sign($studentId = 0) {
		// 节数集合，支持多选，比如：1,2,3,4
        $timeslotSet = $this->get('timeslot') ? $this->get('timeslot') : 0;

        $dateBegin = $this->get('date_begin');
        $dateEnd = $this->get('date_end');
        // 本人登录就获取登录用户id
        $studentId = $studentId ? $studentId : $this->user['id'];
        if($dateBegin > $dateEnd) {
            throw new Exception('开始日期不能大于结束日期');
        }
        // 获取日期数组
        $dateArr = getDateFromRange($dateBegin, $dateEnd);
        if(count($dateArr) > 31) {
            throw new Exception('区间不能超过一个月');
        }

        $studentInfo = $this->schoolModel->get_student_info($studentId);
        if(empty($studentInfo)) throw new Exception('服务异常，请联系管理员');

        $classInfo = $this->classesModel->get_class_info($studentInfo['class_id']);
        // 获取某班每周的上课天数
        $weekArr = $this->classesModel->get_class_schedule_week_arr($classInfo, $timeslotSet);
        // 获取日期区间
        $dateArr = $this->classesModel->get_date_arr_and_filter_week($dateBegin, $dateEnd, $weekArr);

        // 获取考勤数据
        $signParams['schoolId'] = $studentInfo['school_id'];
        $signParams['campusId'] = $studentInfo['campus_id'];
        // $signParams['classId'] = $studentInfo['class_id'];
        // 开始日期
        $signParams['begindate'] = $dateBegin;
        // 结束日期
        $signParams['enddate'] = $dateEnd;
        // 学生id
        $signParams['studentId'] = $studentId;
        // 只获取上课签到，排除闸机，一体机签到
        $signParams['onlySignForClass'] = 1;
        // 只获取重新签到
        $signParams['isRefreshSign'] = 1;
		// 节数集合，支持多选，比如：1,2,3,4
        if($timeslotSet) {
            $signParams['scheduleClassIndexSet'] = $timeslotSet;
        }

        $signArr = $this->dataModel->get_student_sign_list($signParams);

        $dateSignArr = array();
        foreach($dateArr as $date) {
            $signCount = $lateCount = 0;
            foreach($signArr as $sign) {
                if($sign['sign_date'] == $date) {
                    if($sign['is_supplement']) {
                        // 补签
                        $lateCount++;
                    } else {
                        // 正常签到
                        $signCount++;
                    }
                }
            }
            
            // 转换日期格式，2021年6月11日  星期二
            $tempArr = explode('-', $date);
            $dateFormat = $tempArr[0] . '年' . $tempArr[1] . '月' . $tempArr[2] . '日';
            $dateSignArr[$date] = array(
                'sign' => $signCount,
                'late' => $lateCount,
                'week' => date_to_week_format_new($date),
                'date' => $date,
                'dateFormat' => $dateFormat
            );
        }     
        // $signArr = array_reverse($signArr);
        // echo '<pre>';var_export($signArr);exit;
  
        exit(json('', true, $dateSignArr));
    }

    // 已废弃
    public function get_user_sign_old($studentId = 0) {
        $dateBegin = $this->get('date_begin');
        $dateEnd = $this->get('date_end');
        $timeslot = $this->get('timeslot') ? $this->get('timeslot') : 1;
        // 本人登录就获取登录用户id
        $studentId = $studentId ? $studentId : $this->user['id'];
        if($dateBegin > $dateEnd) {
            throw new Exception('开始日期不能大于结束日期');
        }
        // 获取日期数组
        $dateArr = getDateFromRange($dateBegin, $dateEnd);
        if(count($dateArr) > 31) {
            throw new Exception('区间不能超过一个月');
        }
        // $signData = $this->dataModel->get_student_sign($studentId, $dateBegin, $dateEnd);
        // // 数组以签到日期为键
        // $signData = array_value_to_key($signData, 'sign_date');
        // $result = array();
        // foreach($dateArr as $date) {
        //     // 判断是否已签到
        //     $hasSign = isset($signData[$date]);
        //     array_push($result, array(
        //         'date' => $date,
        //         'day' => date_to_week($date),
        //         'has_sign' => $hasSign,
        //         'id' => isset($signData[$date]) ? $signData[$date]['id'] : 0
        //     ));
        // }
        if($studentId) {
            $studentInfo = $this->schoolModel->get_student_info($studentId);
            $classInfo = array();
            if($studentInfo) {
                $classInfo = $this->classesModel->get_class_info($studentInfo['class_id']);
            }
        }

        $result = array();
        // 当前时分秒
        $time = date('H:i:s');
       
        if($studentId) {
            // 教师查看学生考勤
            // 获取之前最近的重新签到课程，包含本节课
            $schduleParams['schoolId'] = $this->user['school_id'];
            if($classInfo) {
                // 兼容不同年级作息
                $schduleParams['gradeId'] = $classInfo['grade_id'];
            }
        } else {
            // 获取之前最近的重新签到课程，包含本节课
            $schduleParams['schoolId'] = $this->user['school_id'];
            // 兼容不同年级作息
            $schduleParams['gradeId'] = $this->user['class']['grade_id'];
        }
  
        $schduleParams['isThisWeek'] = 1;
        $scheduleInfo = $this->classesModel->get_school_schedule_row($schduleParams);
        $timeArr = json_decode($scheduleInfo['schedule_time_json'], true);
        // 上课结束时间
        $lessonEndTime = $this->dataModel->get_lesson_end_time($timeArr, $timeslot);
        // var_export($lessonEndTime);exit;
        foreach($dateArr as $date) {
            $signData = $this->dataModel->get_student_sign_data($date, $studentId, $lessonEndTime);

            // // 之前日期的考勤按最后一节情况
            // $refreshClassIndex = $this->dataModel->get_refresh_class_index($timeArr, $date);
            // 之前日期的考勤都按当前节数算
            $refreshClassIndex = $this->dataModel->get_refresh_class_index($timeArr, date('Y-m-d'), $timeslot);
            if($signData['sign_id']) {
                if($signData['state'] == SIGN_STATE_LEAVE) {
                    // 离校
                    $signData['sign_id'] = 0;
                } else {
                    if($signData['schedule_class_index'] < $refreshClassIndex) {
                        // 重新签到后还没签
                        $signData['sign_id'] = 0;
                    }
                }
            }
            // 判断是否已签到
            $hasSign = !empty($signData['sign_id']);
            array_push($result, array(
                'date' => $date,
                'day' => date_to_week_format_new($date),
                'has_sign' => $hasSign,
                'id' => $signData['sign_id'] ?$signData['sign_id'] : 0
            ));
        }

        exit(json('', true, $result));
    }

        
    /*
     * 签到详情页面v2
    */
    public function student_sign_detail_v2($studentId) {
        $this->htmlTitle = '考勤详情';
        $signdate = $this->get('date') ? $this->get('date') : date('Y-m-d');
        // 获取学生信息
        $studentInfo = $this->schoolModel->get_student_info($studentId);

        // 获取考勤数据
        $signParams['schoolId'] = $studentInfo['school_id'];
        $signParams['campusId'] = $studentInfo['campus_id'];
        // $signParams['classId'] = $studentInfo['class_id'];
        // 签到日期
        $signParams['signdate'] = $signdate;
        // 学生id
        $signParams['studentId'] = $studentId;
        // 只获取上课签到，排除闸机，一体机签到
        $signParams['onlySignForClass'] = 1;
        // 只获取重新签到
        $signParams['isRefreshSign'] = 1;
        $signArr = $this->dataModel->get_student_sign_list($signParams);
        // 颠倒顺序
        $signArr = array_reverse($signArr);

        // 获取本校全部班级
        $classParams['schoolId'] = $studentInfo['school_id'];
        $classParams['campusId'] = $studentInfo['campus_id'];
        $classList = $this->classesModel->get_class_list($classParams);
        $classList = array_value_to_key($classList, 'id');
        foreach($signArr as &$sign) {
            // 获取班级名称
            if(isset($classList[$sign['class_id']])) {
                $sign['className'] = $classList[$sign['class_id']]['class_name'];
            } else {
                $sign['className'] = '';
            }
            // 截取签到时间，分：秒
            $signTime = explode(' ', $sign['createtime'])[1];
            $signH = explode(':', $signTime)[0];
            $signM = explode(':', $signTime)[1];
            $sign['signTimeFormat'] = $signH . ':' . $signM;
        }

        // echo '<pre>';var_export($classList);exit;

        $this->signdate = $signdate;
        $this->week = date_to_week_format_new($signdate);
        $this->studentInfo = $studentInfo;
        $this->signArr = $signArr;

        // 处理温度
        // $this->signInfo['temperature'] = handle_temperature($this->signInfo['temperature']);

        // 获取jssdk参数
        $this->load->library('wechat');
        $url = substr(BASE_URL, 0 , -1) . $_SERVER['REQUEST_URI'];
        $this->dataJssdk = $this->wechat->jssdk_data($url);
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'student_sign_detail_v2');
    }

    /*
    * 招考查询页面
    */
    public function exam_query() {
        // 获取招考查询地址
        $examQueryLink = $this->configModel->get_config_info('exam_query_link', true);
        if(empty($examQueryLink)){
            echo "<script>alert('功能暂未开放');history.go(-1);</script>"; 
            exit; 
        }
        header('Location: ' . $examQueryLink);
    }

    /*
    * 请假管理页面
    */
    public function leave() {
        if(1){
            // echo "<script>alert('功能暂未开放');history.go(-1);</script>";
        }
        // header('Location: ' . $examQueryLink);
    }

    /*
    * 考场安排页面
    */
    public function smart_device() {
        $this->htmlTitle = '智能设备';
        
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . "smart_device");
    }

    /*
     * 留言页面
     */
    public function note() {
        $this->htmlTitle = '对话留言';
        $this->isBrand = 0;
        $this->menuUrl = 'note_dialog';
        $this->_note();

        $this->display(WX_DIR . DIRECTORY_SEPARATOR . "note");
    }

    private function _note() {
        // 连接socket
        $channelId = $this->user['id'] . '_' . $this->bindUserType;
        $dataSource = '_sae/channel/create_channel/'. $channelId;
        $channelData = file_get_contents(web_url($dataSource));
        $channelData = json_decode($channelData, true);
        if(strstr($channelData['data'], '120.25.177.161')) {
            // 非新浪云的socket，不用转换为wss
            $this->socketUrl = $channelData['data'];
        } else {
            $this->socketUrl = str_replace("ws:", "wss:", $channelData['data']);
        }

        // 任课班级
        $this->teacherClassArr = array();
        if($this->bindUserType == BIND_TYPE_TEACHER) {
            // 教师权限
            $this->teacherClassArr = $this->get_classes_by_teacher_id(false, false);
            // echo '<pre>';var_export($this->teacherClassArr);exit;
            if($this->teacherClassArr) {
                foreach($this->teacherClassArr as $key => $class) {
                    // 获取某班级所有学生
                    $stuParams['schoolId'] = $this->user['school_id'];
                    // $stuParams['classId'] = $class['id'];
                    // 包含教学班
                    $stuParams['classORteach'] = $class['id'];
                    $stuParams['isDelete'] = 0;
                    $studentArr = $this->schoolModel->get_student_list($stuParams);
                    if($studentArr) {
                        foreach($studentArr as $k => $student) {
                            // 获取首字母
                            $studentArr[$k]['realnameFirstChar'] = getFirstChar($student['realname']);
                        }
                        // 按姓名首字母排序
                        $timeKey =  array_column($studentArr, 'realnameFirstChar');
                        array_multisort($timeKey, SORT_ASC, $studentArr);
                    }
                    $this->teacherClassArr[$key]['studentArr'] = $studentArr;
                }
            }
        } else {
            // 学生权限
            $classId = $this->user['class']['id'];
            // // 获取该班级的所有任课老师
            // $teacherParams['schoolId'] = $this->user['school_id'];
            // $teacherParams['classId'] = $classId;
            // $teacherParams['isDelete'] = 0;
            // $this->teachingTeacherList = $this->schoolModel->get_teacher_list($teacherParams);

            // 改成执教关系
            // 获取执教关系列表
            $coachParams['classId'] = $classId;
            $this->load->model('staffModel');
            $coachList = $this->staffModel->get_coach_list($coachParams);
            // 获取教师列表
            $teacherParams['isDelete'] = 0;
            $teacherParams['schoolId'] = $this->user['school_id'];
            $teacherList = $this->schoolModel->get_teacher_list($teacherParams);
            // 使用id作为键
            $teacherList = array_value_to_key($teacherList, 'id');
            $teacherArr = array();
            foreach($coachList as $coach) {
                $teacherId = $coach['teacher_id'];
                if(isset($teacherList[$teacherId]) && !in_array($teacherList[$teacherId], $teacherArr)) {
                    array_push($teacherArr, $teacherList[$teacherId]);
                }
            }
            if($teacherArr) {
                foreach($teacherArr as $key => $teacher) {
                    // 获取首字母
                    $teacherArr[$key]['realnameFirstChar'] = getFirstChar($teacher['realname']);
                }
                // 按姓名首字母排序
                $timeKey =  array_column($teacherArr, 'realnameFirstChar');
                array_multisort($timeKey, SORT_ASC, $teacherArr);
            }
            $this->teachingTeacherList = $teacherArr;
        }
        $noteList = $this->wxUserModel->get_user_wx_note_list($this->user['id'], $this->bindUserType, $this->isBrand);
        $filterdNoteList = array();
        $unreadArr = array();
        foreach($noteList as $note) {
            if($note['send_user_id'] == $this->user['id'] && $note['send_user_type'] == $this->bindUserType) {
                $otherUserId = $note['receive_user_id'];
            } else {
                $otherUserId = $note['send_user_id'];
                // 计算未读数
                if($note['has_read'] == 0 && $note['is_delete'] == 0) {
                    if(isset($unreadArr[$otherUserId])) {
                        $unreadArr[$otherUserId] ++;
                    } else {
                        $unreadArr[$otherUserId] = 1;
                    }
                }
            }
            if(!isset($filterdNoteList[$otherUserId])) {
                $filterdNoteList[$otherUserId] = $note; 
            }
        }
        if($filterdNoteList) {
            $classParams['isDelete'] = 0;
            $classParams['schoolId'] = $this->user['school_id'];
            $classList = $this->classesModel->get_class_list($classParams);
            // 使用id作为键值
            $classList = array_value_to_key($classList, 'id');
            foreach($filterdNoteList as $key => $value) {
                // 时间去掉秒
                $filterdNoteList[$key]['createtime'] = time_remove_second($value['createtime']);
                // 获取未读数
                $filterdNoteList[$key]['unread'] = isset($unreadArr[$key]) ? $unreadArr[$key] : 0;
                if($filterdNoteList[$key]['type'] == WX_NOTE_TYPE_TEXT) {
                    $filterdNoteList[$key]['content'] = base64_decode($filterdNoteList[$key]['content']);
                }
                // 获取用户头像
                if($this->bindUserType == BIND_TYPE_STUDENT) {
                    // 获取教师信息
                    $teacher = $this->schoolModel->get_school_user_info_realname($key);
                    $filterdNoteList[$key]['user_id'] = $teacher['id'];
                    // 获取姓名
                    $filterdNoteList[$key]['realname'] = $teacher['realname'];
                    // 获取头像
                    $filterdNoteList[$key]['headimgurl'] = $teacher['headimgurl'];

                    // 过滤已删除教师
                    if(empty($teacher) || $teacher['is_delete'] == 1) {
                        unset($filterdNoteList[$key]);
                    }
                } else {
                    // 获取学生信息
                    $student = $this->schoolModel->get_student_info($key);
                    $filterdNoteList[$key]['user_id'] = $student['id'];
                    // 获取姓名
                    $filterdNoteList[$key]['realname'] = $student['realname'];
                    // 获取头像
                    $filterdNoteList[$key]['headimgurl'] = $student['headimgurl'];

                    // 获取班级名称
                    if(isset($classList[$student['class_id']])) {
                        $classname = $classList[$student['class_id']]['class_name'];
                        $classnameSuffix = '-' . $classname;
                        $filterdNoteList[$key]['realname'] .= $classnameSuffix;
                    }

                    // 过滤已删除学生
                    if(empty($student) || $student['is_delete'] == 1) {
                        unset($filterdNoteList[$key]);
                    }
                }
            }
        }
        $this->filterdNoteList = $filterdNoteList;
        // echo '<pre>';var_export($this->user);exit;
    }

    /*
     * 留言对话框页面
     */
    public function note_dialog($otherUserId) {
        if($this->bindUserType == BIND_TYPE_STUDENT) {
            $otherUserType = BIND_TYPE_TEACHER;
        } else {
            $otherUserType = BIND_TYPE_STUDENT;
        }
        // 连接socket
        $channelId = $otherUserId . '_' . $otherUserType . '_' . $this->user['id'];
        $dataSource = '_sae/channel/create_channel/'. $channelId;
        $channelData = file_get_contents(web_url($dataSource));
        $channelData = json_decode($channelData, true);
        if(strstr($channelData['data'], '120.25.177.161')) {
            // 非新浪云的socket，不用转换为wss
            $this->socketUrl = $channelData['data'];
        } else {
            $this->socketUrl = str_replace("ws:", "wss:", $channelData['data']);
        }

        // 用于保存留言
        $this->isBrand = 0;
        $this->_note_dialog($otherUserId);
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . "note_dialog");
    }

    private function _note_dialog($otherUserId) {
        // 用于翻页
        $this->otherUserId = $otherUserId;
        if($this->bindUserType == BIND_TYPE_STUDENT) {
            $otherUserType = BIND_TYPE_TEACHER;
        } else {
            $otherUserType = BIND_TYPE_STUDENT;
        }
        // 获取对方头像
        if($otherUserType == BIND_TYPE_TEACHER) {
            // 获取教师信息
            $teacher = $this->schoolModel->get_school_user_info_realname($otherUserId);
            // 获取头像
            $otherUserheadimgurl = $teacher['headimgurl'];
            // 获取姓名
            $otherUserRealname = $teacher['realname'];
        } else {
            // 获取学生信息
            $student = $this->schoolModel->get_student_info($otherUserId);
            // 获取头像
            $otherUserheadimgurl = $student['headimgurl'];
            // 获取姓名
            $otherUserRealname = $student['realname'];
        }
        $this->htmlTitle = $otherUserRealname;

        // 添加家长后缀
        if($this->isBrand == 0 && $otherUserType == BIND_TYPE_STUDENT) {
            $this->htmlTitle .= '（家长）';
        }
        // 添加教师后缀
        if($otherUserType == BIND_TYPE_TEACHER) {
            $this->htmlTitle .= '（教师）';
        }

        // 获取留言记录
        $this->noteArr = $this->wxUserModel->get_wx_note_dialog($this->user['id'], $this->bindUserType, $otherUserId, $otherUserType, $this->isBrand);
        if($this->noteArr) {
            // 颠倒顺序
            $this->noteArr = array_reverse($this->noteArr);
            foreach($this->noteArr as &$note) {
                // 时间去掉秒
                $note['createtime'] = time_remove_second($note['createtime']);
                // 判断本人是否发送人
                $note['is_self'] = $note['send_user_id'] == $this->user['id'] ? true : false;
                // 设置头像
                $note['headimgurl'] = $note['send_user_id'] == $this->user['id'] ? $this->user['headimgurl'] : $otherUserheadimgurl;
                if(empty($note['headimgurl'])) {
                    // 若头像为空，设置默认头像
                    $note['headimgurl'] = $this->staticWxUrl . 'assets/img/head.png';
                }
                // 判断是否2分钟内
                $twoMinAgo = date('Y-m-d H:i', time() - 120);
                if($note['createtime'] >= $twoMinAgo) {
                    $note['isCurrent'] = true;
                } else {
                    $note['isCurrent'] = false;
                }
                if($note['type'] == WX_NOTE_TYPE_TEXT) {
                    $note['content'] = base64_decode($note['content']);
                }
            }
        }
        // 判断是否只有一页
        if(count($this->noteArr) == WX_NOTE_PAGE_SIZE) {
            $this->isOnlyOnePage = false;
        } else {
            $this->isOnlyOnePage = true;   
        }
        // 获取jssdk参数
        $this->load->library('wechat');
        $url = substr(BASE_URL, 0 , -1) . $_SERVER['REQUEST_URI'];
        $this->dataJssdk = $this->wechat->jssdk_data($url);
        // 设置文字和图片为已读
        $this->db->update(WxUserModel::$wxNoteTable, array(
            'has_read' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        ), array(
            'has_read' => 0,
            'receive_user_id' => $this->user['id'],
            'send_user_id' => $otherUserId,
            'is_brand' => $this->isBrand,
            'type' => WX_NOTE_TYPE_TEXT
        ));
        $this->db->update(WxUserModel::$wxNoteTable, array(
            'has_read' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        ), array(
            'has_read' => 0,
            'receive_user_id' => $this->user['id'],
            'send_user_id' => $otherUserId,
            'is_brand' => $this->isBrand,
            'type' => WX_NOTE_TYPE_IMG
        ));
        if($this->isBrand) {
            // 推送socket消息到班牌
            $student = $this->schoolModel->get_student_info($otherUserId);
            $class = $this->classesModel->get_class_info($student['class_id']);
            $brandArr = $this->classesModel->get_brand_list(array('classIdSet' => $class['id']));
            if($brandArr) {
                // 推送socket消息到班牌
                $this->load->library('socket');
                $otherUserType = $this->bindUserType == BIND_TYPE_STUDENT ? '家长' : '教师';
                $this->socket->send_brand_note_msg_read($brandArr[0]['id'], $otherUserId, $otherUserType, $this->user['id']);
            }
        } else {
            // 推送socket消息到移动端
            $this->load->library('socket');
            $channelId = $this->user['id'] . '_' . $this->bindUserType . '_' .$otherUserId;
            // $noteInfo = $this->wxUserModel->get_wx_note_info_by_user($otherUserId, $otherUserType, $this->user['id'], $this->isBrand);
            // if($noteInfo) {
            //     $this->socket->send_note_msg_read($channelId, $noteInfo['id'], 0);
            // }
            $this->socket->send_note_msg_read($channelId, '', 0);
        }
    }

    // 设置消息为已读并发socket通知对方
    public function set_note_has_read() {
        $noteId = $this->post('note_id');
        // 获取留言详情
        $noteInfo = $this->wxUserModel->get_wx_note_info($noteId);
        // 设置文字和图片为已读
        $this->db->update(WxUserModel::$wxNoteTable, array(
            'has_read' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        ), array(
            'has_read' => 0,
            'receive_user_id' => $noteInfo['receive_user_id'],
            'send_user_id' => $noteInfo['send_user_id'],
            'is_brand' => $noteInfo['is_brand'],
            'type' => WX_NOTE_TYPE_TEXT
        ));
        $this->db->update(WxUserModel::$wxNoteTable, array(
            'has_read' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        ), array(
            'has_read' => 0,
            'receive_user_id' => $noteInfo['receive_user_id'],
            'send_user_id' => $noteInfo['send_user_id'],
            'is_brand' => $noteInfo['is_brand'],
            'type' => WX_NOTE_TYPE_IMG
        ));
        $this->load->library('socket');
        if($noteInfo['is_brand'] == 1) {
            // 推送socket消息到班牌
            $student = $this->schoolModel->get_student_info($noteInfo['send_user_id']);
            $class = $this->classesModel->get_class_info($student['class_id']);
            $brandArr = $this->classesModel->get_brand_list(array('classIdSet' => $class['id']));
            if($brandArr) {
                // 推送socket消息到班牌
                $otherUserType = $noteInfo['receive_user_type'] == BIND_TYPE_STUDENT ? '家长' : '教师';
                $this->socket->send_brand_note_msg_read($brandArr[0]['id'], $noteInfo['send_user_id'], $otherUserType, $noteInfo['receive_user_id']);
            }
        } else {
            // 推送socket消息到移动端
            $channelId = $noteInfo['receive_user_id'] . '_' . $noteInfo['receive_user_type'] . '_' .$noteInfo['send_user_id'];
            $this->socket->send_note_msg_read($channelId, $noteId, 0);
        }

        exit(json('', true));
    }

    // 设置音频消息为已读并发socket通知对方
    public function set_note_has_read_audio() {
        $noteId = $this->post('note_id');
        // 获取留言详情
        $noteInfo = $this->wxUserModel->get_wx_note_info($noteId);
        // 设置已读
        $this->db->update(WxUserModel::$wxNoteTable, array(
            'has_read' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        ), array(
            'id' => $noteId
        ));
        $this->load->library('socket');
        if($noteInfo['is_brand'] == 1) {
            // 推送socket消息到班牌
            $student = $this->schoolModel->get_student_info($noteInfo['send_user_id']);
            $class = $this->classesModel->get_class_info($student['class_id']);
            $brandArr = $this->classesModel->get_brand_list(array('classIdSet' => $class['id']));
            if($brandArr) {
                // 推送socket消息到班牌
                $otherUserType = $noteInfo['receive_user_type'] == BIND_TYPE_STUDENT ? '家长' : '教师';
                $this->socket->send_brand_note_msg_read($brandArr[0]['id'], $noteInfo['send_user_id'], $otherUserType, $noteInfo['receive_user_id']);
            }
        } else {
            // 推送socket消息到移动端
            $channelId = $noteInfo['receive_user_id'] . '_' . $noteInfo['receive_user_type'] . '_' .$noteInfo['send_user_id'];
            $this->socket->send_note_msg_read_audio($channelId, $noteId, 0);
        }

        exit(json('', true));
    }

    // 加载更多留言
    public function get_more_note() {
        $this->isBrand = 0;
        $this->_get_more_note();
    }

    private function _get_more_note() {
        $page = $this->get('page') ? $this->get('page') : 1;
        $otherUserId = $this->get('other_user_id');
        if($this->bindUserType == BIND_TYPE_STUDENT) {
            $otherUserType = BIND_TYPE_TEACHER;
        } else {
            $otherUserType = BIND_TYPE_STUDENT;
        }
        // 获取对方头像
        if($otherUserType == BIND_TYPE_TEACHER) {
            // 获取教师信息
            $teacher = $this->schoolModel->get_school_user_info_realname($otherUserId);
            // 获取头像
            $otherUserheadimgurl = $teacher['headimgurl'];
        } else {
            // 获取学生信息
            $student = $this->schoolModel->get_student_info($otherUserId);
            // 获取头像
            $otherUserheadimgurl = $student['headimgurl'];
        }
        $noteArr = $this->wxUserModel->get_wx_note_dialog($this->user['id'], $this->bindUserType, $otherUserId, $otherUserType, $this->isBrand, $page);
        if($noteArr) {
            foreach($noteArr as &$note) {
                // 时间去掉秒
                $note['createtime'] = time_remove_second($note['createtime']);
                // 判断本人是否发送人
                $note['is_self'] = $note['send_user_id'] == $this->user['id'] ? true : false;
                // 设置头像
                $note['headimgurl'] = $note['send_user_id'] == $this->user['id'] ? $this->user['headimgurl'] : $otherUserheadimgurl;
                if(empty($note['headimgurl'])) {
                    // 若头像为空，设置默认头像
                    $note['headimgurl'] = $this->staticWxUrl . 'assets/img/head.png';
                }
                // 判断是否2分钟内
                $twoMinAgo = time_remove_second(date('Y-m-d H:i', time() - 120));
                if($note['createtime'] >= $twoMinAgo) {
                    $note['isCurrent'] = true;
                } else {
                    $note['isCurrent'] = false;
                }
                if($note['type'] == WX_NOTE_TYPE_TEXT) {
                    $note['content'] = base64_decode($note['content']);
                }
            }
        }
        exit(json('', true, $noteArr));
    }

    // 保存留言
    public function save_note_action() {
        $type = $this->post('type');
        $content = trim($this->post('content'));
        $receiveUserId = $this->post('receive_user_id');
        $isBrand = $this->post('is_brand');
        $sendUserId = $this->user['id'];
        $sendUserType = $this->bindUserType;
        if($this->bindUserType == BIND_TYPE_TEACHER) {
            $receiveUserType = BIND_TYPE_STUDENT;
        } else {
            $receiveUserType = BIND_TYPE_TEACHER;
        }
        // 判断是否家长给学生留言
        if($isBrand && $this->bindUserType == BIND_TYPE_STUDENT) {
            $data['is_parent'] = 1;
            // 接收用户类型设为学生
            $receiveUserType = BIND_TYPE_STUDENT;
        } else {
            $data['is_parent'] = 0;
        }
        // 入库
        $data['type'] = $type;
        $data['content'] = $type == WX_NOTE_TYPE_TEXT ? base64_encode($content) : $content;
        $data['send_user_id'] = $sendUserId;
        $data['send_user_type'] = $sendUserType;
        $data['receive_user_id'] = $receiveUserId;
        $data['receive_user_type'] = $receiveUserType;
        $data['is_brand'] = $isBrand;
        $data['is_delete'] = 0;
        $data['createtime'] = date('Y-m-d H:i:s');
        $data['updatetime'] = date('Y-m-d H:i:s');
        $this->db->insert(WxUserModel::$wxNoteTable, $data);
        // 须在这里定义，不然会被下面的影响到
        $id = $this->db->insert_id();

        if($isBrand) {
            $student = $this->schoolModel->get_student_info($receiveUserId);
            $class = $this->classesModel->get_class_info($student['class_id']);
            $brandArr = $this->classesModel->get_brand_list(array('classIdSet' => $class['id']));
            if($brandArr) {
                // 推送socket消息到班牌
                $this->load->library('socket');

                if($sendUserType == BIND_TYPE_STUDENT) {
                    $typeChinese = '家长';
                } else {
                    $typeChinese = '教师';
                }
                $this->socket->send_brand_note_msg($brandArr[0]['id'], $id, $type, $content, $receiveUserId, $student['realname'], $typeChinese, $sendUserId, $data['createtime']);
            }
        } else {
            // 获取发送人信息
            if($sendUserType == BIND_TYPE_TEACHER) {
                // 获取教师信息
                $teacher = $this->schoolModel->get_school_user_info_realname($sendUserId);
                // 获取姓名
                $realname = $teacher['realname'];
            } else {
                // 获取学生信息
                $student = $this->schoolModel->get_student_info($sendUserId);
                // 获取头像
                // $realname = $student['realname'] . '家长';
                $realname = $student['realname'];
            }
            $realContent = $content;    // 供socket实时刷新使用
            if($type == WX_NOTE_TYPE_AUDIO) {
                $content = '[语音]';
            } elseif ($type == WX_NOTE_TYPE_IMG) {
                $content = '[图片]';
            }
            $templateId = $this->bindUserType == BIND_TYPE_STUDENT ? WX_TEMPLATE_NOTE_PARENT : WX_TEMPLATE_NOTE_TEACHER;
            $firstValue =  $this->bindUserType == BIND_TYPE_STUDENT ? '您好，收到来自学生家长端的私信：' : '您好，收到新的私信：';
            // 发送模板消息
            // 使用个不用权限的新路径，在里面进行登录，在跳转到 classes/note_dialog/944
            $url = wx_url('pub/note_dialog?send_user_id=' . $sendUserId . '&receive_user_id=' . $receiveUserId .'&receive_user_type=' . $receiveUserType . '&is_brand=0'); 
            // 
            if($this->bindUserType == BIND_TYPE_STUDENT) {
                $tempData = array(
                    'first' => array(
                        'value' => $firstValue,
                        'color' => "#0200C4"
                    ),
                    'keyword1' => array(
                        'value' => $realname
                    ),
                    'keyword2' => array(
                        'value' => $data['createtime']
                    ),
                    'keyword3' => array(
                        'value' => transformBrForNote($content)
                    ),
                    // 'remark' => array(
                    //     'value' => '查看详情'
                    // )
                );
            } else {
                $tempData = array(
                    'first' => array(
                        'value' => $firstValue
                    ),
                    'keyword1' => array(
                        'value' => $realname
                    ),
                    'keyword2' => array(
                        'value' => $data['createtime']
                    ),
                    'keyword3' => array(
                        'value' => transformBrForNote($content)
                    ),
                    // 'remark' => array(
                    //     'value' => '查看详情'
                    // )
                );
            }
          
            $this->load->library('wxtemplate');
            $this->wxtemplate->send_template_msg_for_user($receiveUserId, $receiveUserType, $templateId, $tempData, $url);

            // 推送socket消息到移动端
            $this->load->library('socket');
            $channelId = $sendUserId . '_' . $sendUserType . '_' . $receiveUserId;
            // 获取用户头像
            if($sendUserType == BIND_TYPE_STUDENT) {
                 // 获取学生信息
                 $student = $this->schoolModel->get_student_info($sendUserId);
                 // 获取头像
                 $headimgurl = $student['headimgurl'];
            } else {
                // 获取教师信息
                $teacher = $this->schoolModel->get_school_user_info_realname($sendUserId);
                // 获取头像
                $headimgurl = $teacher['headimgurl'];
            }
            $headimgurl = $headimgurl ? $headimgurl : $this->staticWxUrl . 'assets/img/head.png';
            $this->socket->send_note_msg($channelId, $id, $type, $realContent, $headimgurl, 0, time_remove_second($data['createtime']));
            // 发送给移动端留言列表页面
            $channelIdForList = $receiveUserId . '_' . $receiveUserType;
            $this->socket->send_note_msg_for_list($channelIdForList, $sendUserId, transformBrForNote($content), 0, time_remove_second($data['createtime']));
        }

        // 返回id
        exit(json('', true, array(
            'id' => $id
        )));
    }

    // 撤回留言
    public function delete_note_action() {
        $id = $this->post('id');
        // 获取留言详情
        $noteInfo = $this->wxUserModel->get_wx_note_info($id);
        if(empty($noteInfo)) {
            throw new Exception('留言不存在');
        }

        $this->db->update(WxUserModel::$wxNoteTable, array(
            'is_delete' => 1,
            'updatetime' =>date('Y-m-d H:i:s')
        ), array('id' => $id));

        $this->load->library('socket');
        if($noteInfo['is_brand']) {
            if($noteInfo['receive_user_type'] == BIND_TYPE_STUDENT) {
                // 推送socket消息到班牌
                $studentInfo = $this->schoolModel->get_student_info($noteInfo['receive_user_id']);
                if($studentInfo) {
                    $class = $this->classesModel->get_class_info($studentInfo['class_id']);
                    $brandArr = $this->classesModel->get_brand_list(array('classIdSet' => $class['id']));
                    if($brandArr) {
                        $this->socket->send_brand_note_delete_msg($brandArr[0]['id'], $id);
                    }
                }
            }
        } else {
            // 推送socket消息到移动端
            $channelId = $noteInfo['send_user_id'] . '_' . $noteInfo['send_user_type'] . '_' . $noteInfo['receive_user_id'];
            $this->socket->send_note_delete_msg($channelId, $id, 0);
        // 发送给移动端留言列表页面
        $channelIdForList = $noteInfo['receive_user_id'] . '_' . $noteInfo['receive_user_type'];
        $this->socket->send_note_delete_msg_for_list($channelIdForList, $noteInfo['send_user_id'], 0, time_remove_second(date('Y-m-d H:i:s')));
        }

        exit(json('', true));
    }

    /*
     * 班牌留言页面
     */
    public function brand_note() {
        $this->htmlTitle = '班牌留言';
        $this->isBrand = 1;
        $this->menuUrl = 'brand_note_dialog';
        if($this->bindUserType == BIND_TYPE_TEACHER) {
            $this->_note();
            $this->display(WX_DIR . DIRECTORY_SEPARATOR . "note");
        } else {
            // 连接socket
            $channelId = $this->user['id'] . '_' . BIND_TYPE_STUDENT . '_' . $this->user['id'];
            $dataSource = '_sae/channel/create_channel/'. $channelId;
            $channelData = file_get_contents(web_url($dataSource));
            $channelData = json_decode($channelData, true);
            if(strstr($channelData['data'], '120.25.177.161')) {
                // 非新浪云的socket，不用转换为wss
                $this->socketUrl = $channelData['data'];
            } else {
                $this->socketUrl = str_replace("ws:", "wss:", $channelData['data']);
            }

            $this->_note_dialog_for_parent();
            // 用于翻页
            $this->isParent = 1;
            // 添加后缀
            $this->htmlTitle .= '（教室班牌上）';
            $this->display(WX_DIR . DIRECTORY_SEPARATOR . "note_dialog");
        }
    }

    private function _note_dialog_for_parent() {
        // 用于翻页
        $this->otherUserId = $this->user['id'];
        $this->htmlTitle = $this->user['realname'];

        // 获取留言记录
        $this->noteArr = $this->wxUserModel->get_wx_note_dialog($this->user['id'], BIND_TYPE_STUDENT, $this->user['id'], BIND_TYPE_STUDENT, $this->isBrand);
        if($this->noteArr) {
            // 颠倒顺序
            $this->noteArr = array_reverse($this->noteArr);
            foreach($this->noteArr as &$note) {
                // 时间去掉秒
                $note['createtime'] = time_remove_second($note['createtime']);
                // 判断本人是否发送人
                $note['is_self'] = $note['is_parent'] ? true : false;
                // 设置头像
                $note['headimgurl'] = $this->user['headimgurl'];
                if(empty($note['headimgurl'])) {
                    // 若头像为空，设置默认头像
                    $note['headimgurl'] = $this->staticWxUrl . 'assets/img/head.png';
                }
                // 判断是否2分钟内
                $twoMinAgo = date('Y-m-d H:i', time() - 120);
                if($note['createtime'] >= $twoMinAgo) {
                    $note['isCurrent'] = true;
                } else {
                    $note['isCurrent'] = false;
                }
                if($note['type'] == WX_NOTE_TYPE_TEXT) {
                    $note['content'] = base64_decode($note['content']);
                }
            }
        }
        // 判断是否只有一页
        if(count($this->noteArr) == WX_NOTE_PAGE_SIZE) {
            $this->isOnlyOnePage = false;
        } else {
            $this->isOnlyOnePage = true;   
        }
        // 获取jssdk参数
        $this->load->library('wechat');
        $url = substr(BASE_URL, 0 , -1) . $_SERVER['REQUEST_URI'];
        $this->dataJssdk = $this->wechat->jssdk_data($url);
        // 设置文字和图片为已读
        $this->db->update(WxUserModel::$wxNoteTable, array(
            'has_read' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        ), array(
            'has_read' => 0,
            'receive_user_id' => $this->user['id'],
            'send_user_id' => $this->user['id'],
            'is_brand' => $this->isBrand,
            'is_parent' => 0,
            'type' => WX_NOTE_TYPE_TEXT
        ));
        $this->db->update(WxUserModel::$wxNoteTable, array(
            'has_read' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        ), array(
            'has_read' => 0,
            'receive_user_id' => $this->user['id'],
            'send_user_id' => $this->user['id'],
            'is_brand' => $this->isBrand,
            'is_parent' => 0,
            'type' => WX_NOTE_TYPE_IMG
        ));
        $student = $this->schoolModel->get_student_info($this->user['id']);
        $class = $this->classesModel->get_class_info($student['class_id']);
        $brandArr = $this->classesModel->get_brand_list(array('classIdSet' => $class['id']));
        if($brandArr) {
            // 推送socket消息到班牌
            $this->load->library('socket');
            $this->socket->send_brand_note_msg_read($brandArr[0]['id'], $this->user['id'], '家长', $this->user['id']);
        }
    }

    // 加载更多班牌家长留言
    public function get_more_brand_note_for_parent() {
        $this->isBrand = 1;
        $page = $this->get('page') ? $this->get('page') : 1;
        $this->otherUserId = $this->user['id'];
        // 获取留言记录
        $noteArr = $this->wxUserModel->get_wx_note_dialog($this->user['id'], BIND_TYPE_STUDENT, $this->user['id'], BIND_TYPE_STUDENT, $this->isBrand, $page);
        if($noteArr) {
            foreach($noteArr as &$note) {
                // 时间去掉秒
                $note['createtime'] = time_remove_second($note['createtime']);
                // 判断本人是否发送人
                $note['is_self'] = $note['is_parent'] ? true : false;
                // 设置头像
                $note['headimgurl'] = $this->user['headimgurl'];
                if(empty($note['headimgurl'])) {
                    // 若头像为空，设置默认头像
                    $note['headimgurl'] = $this->staticWxUrl . 'assets/img/head.png';
                }
                // 判断是否2分钟内
                $twoMinAgo = date('Y-m-d H:i', time() - 120);
                if($note['createtime'] >= $twoMinAgo) {
                    $note['isCurrent'] = true;
                } else {
                    $note['isCurrent'] = false;
                }
                if($note['type'] == WX_NOTE_TYPE_TEXT) {
                    $note['content'] = base64_decode($note['content']);
                }
            }
        }
        exit(json('', true, $noteArr));
    }

    /*
     * 班牌留言对话框页面
     */
    public function brand_note_dialog($otherUserId) {
        if($this->bindUserType == BIND_TYPE_STUDENT) {
            $otherUserType = BIND_TYPE_TEACHER;
        } else {
            $otherUserType = BIND_TYPE_STUDENT;
        }
        // 连接socket
        $channelId = $otherUserId . '_' . $otherUserType . '_' . $this->user['id'];
        $dataSource = '_sae/channel/create_channel/'. $channelId;
        $channelData = file_get_contents(web_url($dataSource));
        $channelData = json_decode($channelData, true);
        if(strstr($channelData['data'], '120.25.177.161')) {
            // 非新浪云的socket，不用转换为wss
            $this->socketUrl = $channelData['data'];
        } else {
            $this->socketUrl = str_replace("ws:", "wss:", $channelData['data']);
        }

        // 用于保存留言
        $this->isBrand = 1;
        $this->_note_dialog($otherUserId);
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . "note_dialog");
    }

    // 加载更多班牌留言
    public function get_more_brand_note() {
        $this->isBrand = 1;
        $this->_get_more_note();
    }

    // /*
    // * 班牌广播页面
    // */
    // public function broadcast() {
    //     if($this->bindUserType == BIND_TYPE_STUDENT) {
    //         $this->htmlTitle = '家长留言';
    //     } else {
    //         $this->htmlTitle = '教师留言';
    //     }
        
    //     $this->display(WX_DIR . DIRECTORY_SEPARATOR . "broadcast");
    // }


    // // 获取通知列表
    // public function get_broadcast_list() {
    //     $pageStart = $this->get('pageStart');
    //     $pageSize = $this->get('pageSize');
    //     $broadcastList  = array();
    //     $params['isDelete'] = 0;
    //     $params['pageStart'] = !empty($pageStart) ? $pageStart : 0;
    //     $params['pageSize'] = !empty($pageSize) ? $pageSize : 5;
    //     $params['userId'] = $this->user['id'];
    //     $params['bindUserType'] = $this->bindUserType;
    //     $broadcastList = $this->wxUserModel->get_wx_brand_broadcast_list($params);
    //     foreach($broadcastList as &$broadcast) {
    //         // 转换updatetime为格式：2019.10.10
    //         $broadcast['updatetimeFormat'] = format_time_to_date($broadcast['updatetime']);
    //         // 获取通知学生
    //         $broadcast['studentNameStr'] = $this->_get_student_name_str($broadcast['student_ids']);
    //     }
    //     exit(json('', true, $broadcastList));
    // }

    // /*
    // * 发布广播页面
    // */
    // public function broadcast_send() {
    //     $this->htmlTitle = '发布留言';
    //     // 判断是发布还是编辑
    //     $this->broadcast = array();
    //     $broadcastStudentIdArr = array();
    //     if(!empty($this->get('id'))) {
    //         // 编辑
    //         $broadcast = $this->wxUserModel->get_wx_brand_broadcast_info($this->get('id'));
    //         // 获取通知学生
    //         $broadcast['studentNameStr'] = $this->_get_student_name_str($broadcast['student_ids']);
    //         // 截止时间去掉秒
    //         $broadcast['endtime'] = time_remove_second($broadcast['endtime']);
    //         $this->broadcast = $broadcast;
    //         $broadcastStudentIdArr = explode(',', $broadcast['student_ids']);
    //     }
    //     // 任课班级
    //     $this->teacherClassArr = array();
    //     if($this->bindUserType == BIND_TYPE_TEACHER) {
    //         $this->teacherClassArr = $this->get_classes_by_teacher_id();
    //         if($this->teacherClassArr) {
    //             foreach($this->teacherClassArr as &$class) {
    //                 // 获取某班级所有学生
    //                 $stuParams['schoolId'] = $this->user['school_id'];
    //                 $stuParams['classId'] = $class['id'];
    //                 $stuParams['isDelete'] = 0;
    //                 $class['studentArr'] = $this->schoolModel->get_student_list($stuParams);
    //                 if($class['studentArr']) {
    //                     foreach($class['studentArr'] as &$student) {
    //                         // 获取首字母
    //                         $student['realnameFirstChar'] = getFirstChar($student['realname']);
    //                         // 判断该学生是否已选中
    //                         if($broadcastStudentIdArr && in_array($student['id'], $broadcastStudentIdArr)) {
    //                             $student['selected'] = true;
    //                         } else {
    //                             $student['selected'] = false;
    //                         }
    //                     }
    //                     // 按姓名首字母排序
    //                     $timeKey =  array_column($class['studentArr'], 'realnameFirstChar');
    //                     array_multisort($timeKey, SORT_ASC, $class['studentArr']);
    //                 }
    //             }
    //         }
    //     }
        
    //     $this->display(WX_DIR . DIRECTORY_SEPARATOR . "broadcast_send");
    // }

    // // 保存广播操作
    // public function save_broadcast_action() {
    //     $id = $this->post('id');
    //     $studentIds = $this->post('studentIds');
    //     $content = trim($this->post('content'));
    //     $endTime = $this->post('endTime');
    //     // 家长留言
    //     if($this->bindUserType == BIND_TYPE_STUDENT) {
    //         $studentIds = $this->user['id'];
    //     }
    //     if(empty($studentIds)) {
    //         throw new Exception('发布学生不能为空');
    //     }
    //     if(empty($content)) {
    //         throw new Exception('内容不能为空');
    //     }
    //     // 入库
    //     $data = array(
    //         'is_delete' => 0,
    //         'user_id' => $this->user['id'],
    //         'bind_user_type' => $this->bindUserType,
    //         'content' => $content,
    //         'endtime' => $endTime,
    //         'student_ids' => $studentIds,
    //         'updatetime' => date('Y-m-d H:i:s')
    //     );
    //     if(empty($id)) {
    //         // 插入
    //         $data['createtime'] = date('Y-m-d H:i:s');
    //         $this->db->insert(WxUserModel::$wxBrandBroadcastTable, $data);
    //     } else {
    //         // 更新
    //         $this->db->update(WxUserModel::$wxBrandBroadcastTable, $data, array('id' => $id));
    //     }
    //     // 推送消息到客户端
    //     $this->_send_broadcast_socket($studentIds);
    //     exit(json('发布成功', true));
    // }

    // // 删除广播操作
    // public function delete_broadcast_action() {
    //     $id = $this->post('id');
    //     $data = array(
    //         'id' => $id,
    //         'is_delete' => 1,
    //         'updatetime' => date('Y-m-d H:i:s')
    //     );
    //     $this->db->update(WxUserModel::$wxBrandBroadcastTable, $data, array('id' => $id));
    //     $broadcast = $this->wxUserModel->get_wx_brand_broadcast_info($id);
    //     $studentIds = $broadcast['student_ids'];
    //     // 推送消息到客户端
    //     $this->_send_broadcast_socket($studentIds);
    //     exit(json('删除成功', true));
    // }

    // private function _send_broadcast_socket($studentIds) {
    //     $this->load->library('socket');
    //     // 获取学生所在班级
    //     $classIdArr = array();
    //     $studentIdArr = explode(',', $studentIds);
    //     foreach($studentIdArr as $studentId) {
    //         $student = $this->schoolModel->get_student_info($studentId);
    //         $classId = $student['class_id'];
    //         if(!in_array($classId, $classIdArr)) {
    //             array_push($classIdArr, $classId);
    //         }
    //     }
    //     $classIdSet = implode(',', $classIdArr);
    //     $this->socket->send_broadcast_msg($classIdSet);
    // }

    // /*
    // * 留言详情页面
    // */
    // public function broadcast_detail($id) {
    //     if($this->bindUserType == BIND_TYPE_STUDENT) {
    //         $this->htmlTitle = '家长留言详情';
    //     } else {
    //         $this->htmlTitle = '教师留言详情';
    //     }
    //     // 获取留言详情
    //     $broadcast = $this->wxUserModel->get_wx_brand_broadcast_info($id);
    //     // 转换updatetime为格式：2019.10.10
    //     $broadcast['updatetimeFormat'] = format_time_to_date($broadcast['updatetime']);
    //     // 获取通知学生
    //     $broadcast['studentNameStr'] = $this->_get_student_name_str($broadcast['student_ids']);
    //     // 截止时间去掉秒
    //     $broadcast['endtime'] = time_remove_second($broadcast['endtime']);
    //     $this->broadcast = $broadcast;
    //     $this->display(WX_DIR . DIRECTORY_SEPARATOR . "broadcast_detail");
    // }

    /*
     * 我的成绩大项列表页面
    */
    public function my_result() {
        $this->htmlTitle = '成绩项';
        // 获取成绩项数据
        $this->resultMajorList = $this->dataModel->get_result_list_by_student_id($this->user['id']);
        // if(count($this->resultMajorList) == 1) {
        //     header("Location: " . wx_url("classes/my_result_detail/") . $this->resultMajorList[0]['id']);
        // }
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'my_result_major');
    }

    /*
     * 我的成绩页面
    */
    public function my_result_detail($majorId) {
        // if($this->get('user_id') && $this->get('bind_user_type')) {
        //     // 点击模板消息，自动登录用户
        //     $studentInfo = $this->schoolModel->get_student_info($this->get('user_id'));
        //     // session设置登录的user
        //     $wxSession = $this->session->userdata('wx');
        //     if(empty($wxSession)) {
        //         $sessArr = array(
        //             'user' => $studentInfo,
        //             'bind_user_type' => BIND_TYPE_STUDENT
        //         );
        //     } else {
        //         $sessArr = array_merge($this->wxSession, array(
        //             'user' => $studentInfo,
        //             'bind_user_type' => BIND_TYPE_STUDENT
        //         ));
        //     }
        //     $this->session->set_userdata('wx', $sessArr);
        // }

        $majorInfo = $this->dataModel->get_result_major_info($majorId);
        $this->htmlTitle = $majorInfo['title'];
        $studentId = $this->get('student_id');
        if(empty($studentId)) {
            $studentId = $this->user['id'];
        }
        // 获取我的成绩数据
        $result = $this->dataModel->get_result_info_by_major_id($majorId, $studentId);
        if($result) {
            // 获取各科科目
            $resultGradeInfo = $this->dataModel->get_result_grade_info($result['result_grade_id']);
            $subjectIdArr = explode(',', $resultGradeInfo['subject_ids']);
            // 处理value格式
            $valueArr = json_decode($result['value'], true);
            // foreach($valueArr as $key => $item) {
            //     unset($valueArr[$key]['subject_id']);
            // }
            // 没设置分数的科目，设置默认值0
            $valueArr = array_value_to_key($valueArr, 'subject_id');
            foreach($subjectIdArr as $subjectId) {
                if(!isset($valueArr[$subjectId])) {
                    $subjectInfo = $this->schoolModel->get_lesson_info($subjectId);
                    if($subjectInfo) {
                        $valueArr[$subjectId]['subject_id'] = $subjectId;
                        $valueArr[$subjectId]['subject_name'] = $subjectInfo['lesson_name'];
                        $valueArr[$subjectId]['score'] = 0;
                    }
                }
            }
            $result['value'] = $valueArr;

            // 处理total格式
            if(strstr($result['total'], '.0')) {
                $result['total'] = explode('.', $result['total'])[0];
            }
            // 判断是否显示年级排名
            if($result['show_grade_rank']) {
                // 获取年级所有成绩
                $gradeResultList = $this->dataModel->get_result_list(array(
                    'resultGradeId' => $result['result_grade_id'],
                    'isDelete' => 0,
                    'orderBy' => '`total` DESC'
                ));
                foreach($gradeResultList as $key => $item) {
                    $gradeResultList[$key]['rank'] = $key + 1;
                    // 处理并列排名问题
                    $loop = true;
                    $i = 1;
                    while($loop) {
                        if($key - $i >= 0) {
                            if($gradeResultList[$key]['total'] == $gradeResultList[$key - $i]['total']) {
                                $gradeResultList[$key]['rank'] --;
                                $i++;
                            } else {
                                $loop = false;
                            }
                        } else {
                            $loop = false;
                        }
                    }
                    // 各科年级排名
                    $subjectScoreArr = json_decode($item['value'], true);
                    $subjectScoreArr = array_value_to_key($subjectScoreArr, 'subject_id');
                    foreach($subjectIdArr as $subjectId) {
                        if(isset($subjectScoreArr[$subjectId])) {
                            $gradeResultList[$key][$subjectId] = $subjectScoreArr[$subjectId]['score'];
                        } else {
                            $gradeResultList[$key][$subjectId] = 0;
                        }
                    }
                }
                // 用id作为键值
                $gradeResultList = array_value_to_key($gradeResultList, 'id');
                // 年级排名
                $result['grade_rank'] = $gradeResultList[$result['id']]['rank'];
                // 各科年级排名
                $gradeResultListSortArr = array();
                foreach($subjectIdArr as $subjectId) {
                    $timeKey =  array_column($gradeResultList, (int) $subjectId);
                    array_multisort($timeKey, SORT_DESC, $gradeResultList);
                    $gradeResultListSortArr[$subjectId] = $gradeResultList;
                }
                foreach($gradeResultListSortArr as $key => $gradeResultListSort) {
                    foreach($gradeResultListSort as $key2 => $value) {
                        if($value['student_id'] == $studentId) {
                            $rank = $key2 + 1;
                            // 处理并列排名问题
                            $loop = true;
                            $i = 1;
                            while($loop) {
                                if($key2 - $i >= 0) {
                                    if($gradeResultListSort[$key2][$key] == $gradeResultListSort[$key2 - $i][$key]) {
                                        $rank --;
                                        $i++;
                                    } else {
                                        $loop = false;
                                    }
                                } else {
                                    $loop = false;
                                }
                            }
                            $result['suject_id_grade_rank_arr'][$key] = $rank;
                        }
                    }
                }
            }
            // 判断是否显示班级排名
            if($result['show_class_rank']) {
                // 获取年级所有成绩
                $classResultList = $this->dataModel->get_result_list(array(
                    'resultGradeId' => $result['result_grade_id'],
                    'classId' => $result['class_id'],
                    'isDelete' => 0,
                    'orderBy' => '`total` DESC'
                ));
                foreach($classResultList as $key => $item) {
                    $classResultList[$key]['rank'] = $key + 1;
                    // 处理并列排名问题
                    $loop = true;
                    $i = 1;
                    while($loop) {
                        if($key - $i >= 0) {
                            if($classResultList[$key]['total'] == $classResultList[$key - $i]['total']) {
                                $classResultList[$key]['rank'] --;
                                $i++;
                            } else {
                                $loop = false;
                            }
                        } else {
                            $loop = false;
                        }
                    }
                    // 各科班级排名
                    $subjectScoreArr = json_decode($item['value'], true);
                    $subjectScoreArr = array_value_to_key($subjectScoreArr, 'subject_id');
                    foreach($subjectIdArr as $subjectId) {
                        if(isset($subjectScoreArr[$subjectId])) {
                            $classResultList[$key][$subjectId] = $subjectScoreArr[$subjectId]['score'];
                        } else {
                            $classResultList[$key][$subjectId] = 0;
                        }
                    }
                }
                // 用id作为键值
                $classResultList = array_value_to_key($classResultList, 'id');
                // 班级排名
                $result['class_rank'] = $classResultList[$result['id']]['rank'];
                // 各科班级排名
                $classResultListSortArr = array();
                foreach($subjectIdArr as $subjectId) {
                    $timeKey =  array_column($classResultList, (int) $subjectId);
                    array_multisort($timeKey, SORT_DESC, $classResultList);
                    $classResultListSortArr[$subjectId] = $classResultList;
                }
                foreach($classResultListSortArr as $key => $classResultListSort) {
                    foreach($classResultListSort as $key2 => $value) {
                        if($value['student_id'] == $studentId) {
                            $rank = $key2 + 1;
                            // 处理并列排名问题
                            $loop = true;
                            $i = 1;
                            while($loop) {
                                if($key2 - $i >= 0) {
                                    if($classResultListSort[$key2][$key] == $classResultListSort[$key2 - $i][$key]) {
                                        $rank --;
                                        $i++;
                                    } else {
                                        $loop = false;
                                    }
                                } else {
                                    $loop = false;
                                }
                            }
                            $result['suject_id_class_rank_arr'][$key] = $rank;
                        }
                    }
                }
            }
            unset($result['show_grade_rank']);
            unset($result['show_class_rank']);
            unset($result['updatetime']);
            unset($result['is_delete']);
            unset($result['result_grade_id']);
        }
        $this->result = $result;

        // var_export($result);exit;
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'my_result_detail');
    }

    /*
     * 成绩成绩大项列表页面
    */
    public function result() {
        $this->htmlTitle = '成绩项';
        // 任课班级
        $teacherClassArr = $this->get_classes_by_teacher_id();
        // $teacherClassIdArr = array();
        // foreach($teacherClassArr as $class) {
        //     array_push($teacherClassIdArr, $class['id']);
        // }
        // if($teacherClassIdArr) {
        //     $classIds = implode(',', $teacherClassIdArr);
        // } else {
        //     $classIds = '0';
        // }
        $teacherGradeIdArr = array();
        foreach($teacherClassArr as $class) {
            if(!in_array($class['grade_id'], $teacherGradeIdArr))
            array_push($teacherGradeIdArr, $class['grade_id']);
        }
        if($teacherGradeIdArr) {
            $gradeIds = implode(',', $teacherGradeIdArr);
        } else {
            $gradeIds = '0';
        }
        // 获取班级成绩项数据
        $this->resultMajorList = $this->dataModel->get_result_major_list_by_grade_ids($gradeIds);
        // echo '<pre>';var_export($this->resultMajorList);exit;
        // if(count($this->resultMajorList) == 1) {
        //     header("Location: " . wx_url("classes/class_result_detail/") . $this->resultMajorList[0]['id']);
        // }
        // 任课班级
        $this->teacherClassArr = $this->get_classes_by_teacher_id();
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'class_result_major');
    }

    /*
     * 班级成绩页面
    */
    public function class_result_detail($majorId) {
        $classId = $this->get('class_id');
        $majorInfo = $this->dataModel->get_result_major_info($majorId);
        $this->htmlTitle = $majorInfo['title'];
        $this->majorId = $majorId;
        $class = array();
        if($classId) {
            // 获取班级信息
            $class = $this->classesModel->get_class_info($classId);
        }
        // 任课班级
        $teacherClassArr = $this->get_classes_by_teacher_id();
        // 获取年级项列表
        $resultGradeParams['majorId'] = $majorId;
        $resultGradeList = $this->dataModel->get_result_grade_list($resultGradeParams);
        $gradeIdArr = array();
        foreach($resultGradeList as $resultGrade) {
            array_push($gradeIdArr, $resultGrade['grade_id']);
        }
        // 过滤没有年级项的班级
        foreach($teacherClassArr as $key => $teacherClass) {
            if(!in_array($teacherClass['grade_id'], $gradeIdArr)) {
                unset($teacherClassArr[$key]);
            }
        }
        // 重置数组为连续数字索引
        $this->teacherClassArr = array_values($teacherClassArr);
        if(empty($class) && !empty($this->teacherClassArr)) {
            // 如未筛选某个班级，默认选择第一个班级
            $class = $this->teacherClassArr['0'];
            $classId = $class['id'];
        }
        // var_export($class);exit;
        $this->class = $class;
        // 判断是否是该班班主任
        $coachParams['teacherId'] = $this->user['id'];
        $coachParams['classId'] = $classId;
        $coachParams['coachType'] = COACH_TYPE_MASTER;
        $coachList = $this->staffModel->get_coach_list($coachParams);
        if($coachList) {
            $this->isMaster = true;
        } else {
            $this->isMaster = false;
        }
        // 获取班级成绩列表数据
        $resultList = $this->dataModel->get_result_list_by_class_id($majorId, $classId);
                // echo '<pre>';var_export($resultList);exit;
        if($resultList) {
            // 获取各科科目
            $resultGradeInfo = $this->dataModel->get_result_grade_info($resultList[0]['result_grade_id']);
            $subjectIdArr = explode(',', $resultGradeInfo['subject_ids']);
            foreach($resultList as &$result) {
                // 处理value格式
                $valueArr = json_decode($result['value'], true);
                // 使用subject_id作为键值
                $valueArr = array_value_to_key($valueArr, 'subject_id');
                $result['value'] = $valueArr;
                // 处理total格式
                if(strstr($result['total'], '.0')) {
                    $result['total'] = explode('.', $result['total'])[0];
                }

                foreach($subjectIdArr as $subjectId) {
                    // 不存在的科目成绩设置为0
                    if(!isset($result['value'][$subjectId])) {
                        $result['value'][$subjectId] = array(
                            'subject_id' => $subjectId,
                            'score' => 0
                        );
                    }
                }
                // 判断是否显示年级排名
                if($result['show_grade_rank']) {
                    // 获取年级所有成绩
                    $gradeResultList = $this->dataModel->get_result_list(array(
                        'resultGradeId' => $resultGradeInfo['id'],
                        'isDelete' => 0,
                        'orderBy' => '`total` DESC'
                    ));
                    foreach($gradeResultList as $key => $item) {
                        $gradeResultList[$key]['rank'] = $key + 1;
                        // 处理并列排名问题
                        $loop = true;
                        $i = 1;
                        while($loop) {
                            if($key - $i >= 0) {
                                if($gradeResultList[$key]['total'] == $gradeResultList[$key - $i]['total']) {
                                    $gradeResultList[$key]['rank'] --;
                                    $i++;
                                } else {
                                    $loop = false;
                                }
                            } else {
                                $loop = false;
                            }
                        }
                        // 各科年级排名
                        $subjectScoreArr = json_decode($item['value'], true);
                        $subjectScoreArr = array_value_to_key($subjectScoreArr, 'subject_id');
                        foreach($subjectIdArr as $subjectId) {
                            if(isset($subjectScoreArr[$subjectId])) {
                                $gradeResultList[$key][$subjectId] = $subjectScoreArr[$subjectId]['score'];
                            } else {
                                $gradeResultList[$key][$subjectId] = 0;
                            }
                        }
                    }
                    // 用id作为键值
                    $gradeResultList = array_value_to_key($gradeResultList, 'id');
                    // 年级排名
                    $rank = '';
                    if(isset($gradeResultList[$result['id']]['rank'])) {
                        $rank  = $gradeResultList[$result['id']]['rank'];
                    }
                    $result['grade_rank'] = $rank;
                    // 各科年级排名
                    $gradeResultListSortArr = array();
                    foreach($subjectIdArr as $subjectId) {
                        $timeKey =  array_column($gradeResultList, (int) $subjectId);
                                    // echo '<pre>';var_export($timeKey);exit;
                        array_multisort($timeKey, SORT_DESC, $gradeResultList);
                        $gradeResultListSortArr[$subjectId] = $gradeResultList;
                    }

                    foreach($gradeResultListSortArr as $key => $gradeResultListSort) {
                        foreach($gradeResultListSort as $key2 => $value) {
                                                // var_export($value);exit;
                            if($value['student_id'] == $result['student_id']) {
                                $rank = $key2 + 1;
                                // 处理并列排名问题
                                $loop = true;
                                $i = 1;
                                while($loop) {
                                    if($key2 - $i >= 0) {
                                        if($gradeResultListSort[$key2][$key] == $gradeResultListSort[$key2 - $i][$key]) {
                                            $rank --;
                                            $i++;
                                        } else {
                                            $loop = false;
                                        }
                                    } else {
                                        $loop = false;
                                    }
                                }
                                $result['suject_id_grade_rank_arr'][$key] = $rank;
                            }
                        }
                    }
                }

                $result['seat_no'] = intval($result['seat_no']);
            }
            // echo '<pre>';var_export($resultList);exit;
            foreach($resultList as $key => $item) {
                if($result['show_class_rank']) {
                    $resultList[$key]['class_rank'] = $key + 1;
                    // 处理并列排名问题
                    $loop = true;
                    $i = 1;
                    while($loop) {
                        if($key - $i >= 0) {
                            if($resultList[$key]['total'] == $resultList[$key - $i]['total']) {
                                $resultList[$key]['class_rank'] --;
                                $i++;
                            } else {
                                $loop = false;
                            }
                        } else {
                            $loop = false;
                        }
                    }

                    // 各科班级排名
                    // $subjectScoreArr = json_decode($item['value'], true);
                    // $subjectScoreArr = array_value_to_key($subjectScoreArr, 'subject_id');
                    foreach($subjectIdArr as $subjectId) {
                        if(isset($item['value'][$subjectId])) {
                            $resultList[$key][$subjectId] = $item['value'][$subjectId]['score'];
                        } else {
                            $resultList[$key][$subjectId] = 0;
                        }
                    }
                }
            }
            // echo '<pre>';var_export($resultList);exit;
            if($resultList[0]['show_class_rank']) {
                $tempResultList = $resultList;
                // 各科班级排名
                $classResultListSortArr = array();
                foreach($subjectIdArr as $subjectId) {
                    $timeKey =  array_column($tempResultList, (int) $subjectId);
                    array_multisort($timeKey, SORT_DESC, $tempResultList);
                    $classResultListSortArr[$subjectId] = $tempResultList;
                }
                foreach($classResultListSortArr as $key => $classResultListSort) {
                    foreach($classResultListSort as $key2 => $value) {
                        foreach($resultList as $resultKey => $tempResult) {
                            if($value['student_id'] == $tempResult['student_id']) {
                                $rank = $key2 + 1;
                                // 处理并列排名问题
                                $loop = true;
                                $i = 1;
                                while($loop) {
                                    if($key2 - $i >= 0) {
                                        if($classResultListSort[$key2][$key] == $classResultListSort[$key2 - $i][$key]) {
                                            $rank --;
                                            $i++;
                                        } else {
                                            $loop = false;
                                        }
                                    } else {
                                        $loop = false;
                                    }
                                }
                                $resultList[$resultKey]['suject_id_class_rank_arr'][$key] = $rank;
                            }
                        }

                    }
                }
            }
            // echo '<pre>';var_export($resultList);exit;
        }

        if($resultList) {
            // // 暂时按学号排序
            // $timeKey =  array_column($resultList, 'username');

            // 暂时按座位号排序
            $timeKey =  array_column($resultList, 'seat_no');

            array_multisort($timeKey, SORT_ASC, $resultList);
        }
        // echo '<pre>';var_export($resultList);exit;
        $this->resultList = $resultList;
        if($resultList) {
            $resultGradeInfo = $this->dataModel->get_result_grade_info($resultList[0]['result_grade_id']);
            $reulstSubjectIds = $resultGradeInfo['subject_ids'];
            $reulstSubjectIdArr = explode(',', $reulstSubjectIds);
            // 获取科目列表
            $lessonParams['schoolId'] = $this->user['school_id'];
            $lessonParams['isDelete'] = 0;
            $subjectList = $this->schoolModel->get_lesson_list($lessonParams);
            // 使用id作为键值
            $subjectList = array_value_to_key($subjectList, 'id');
            $resultSubjectArr = array();
            foreach($reulstSubjectIdArr as $id) {
                if(isset($subjectList[$id])) {
                    $resultSubjectArr[] = array(
                        'id' => $id,
                        'name' => $subjectList[$id]['lesson_name']
                    );
                }
            }
            $this->resultSubjectArr = $resultSubjectArr;
        }
        // echo '<pre>';var_export($resultList);exit;
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'class_result_detail');
    }

    /*
     * 选择成绩科目页面
    */
    public function choose_result_subject() {
        $this->htmlTitle = '选择科目';
        $this->load->model('staffModel');
        $majorId = $this->get('major_id');
        $classId = $this->get('class_id');

        // 获取年级信息
        $classInfo = $this->classesModel->get_class_info($classId);
        // 获取年级项
        $resultGradeParams['majorId'] = $majorId;
        $resultGradeParams['gradeId'] = $classInfo['grade_id'];
        $resultGradeList = $this->dataModel->get_result_grade_list($resultGradeParams);
        $resultGrade = $resultGradeList[0];
        $subjectIdArr = explode(',', $resultGrade['subject_ids']);
        // 获取执教关系
        $coachParams['teacherId'] = $this->user['id'];
        $coachParams['classId'] = $classId;
        $coachParams['coachType'] = COACH_TYPE_MASTER;
        $coachList = $this->staffModel->get_coach_list($coachParams);
        $resultSubjectIdArr = array();
        if(empty($coachList)) {
            // 发布任课班级对应的科目
            $coachParams['coachType'] = COACH_TYPE_TEACHER;
            $coachList = $this->staffModel->get_coach_list($coachParams);
            $coach = $coachList[0];
            $coachSubjectIdArr = explode(',', $coach['subject_ids']);
            foreach($coachSubjectIdArr as $subjectId) {
                if(in_array($subjectId, $subjectIdArr)) {
                    array_push($resultSubjectIdArr, $subjectId);
                }
            }
        } else {
            // 班主任可发布所有科目
            $resultSubjectIdArr = $subjectIdArr;
        }

        // 获取学校所有科目
        $lesParams['schoolId'] = $this->user['school_id'];
        $lesParams['isDelete'] = 0;
        $subjectArr = $this->schoolModel->get_lesson_list($lesParams);
        // 使用id作为键值
        $subjectArr = array_value_to_key($subjectArr, 'id');
        $resultSubjectArr = array();
        foreach($resultSubjectIdArr as $resultSubjectId) {
            if(isset($subjectArr[$resultSubjectId])) {
                $resultSubjectArr[] = array(
                    'id' => $resultSubjectId,
                    'name' => $subjectArr[$resultSubjectId]['lesson_name']
                );
            }
        }
        $this->resultSubjectArr = $resultSubjectArr;
        $this->resultGradeId = $resultGrade['id'];
        $this->classId = $classId;
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'choose_result_subject');
        // var_export($resultSubjectArr);exit;
    }
    /*
     * 录入成绩页面
    */
    public function import_result() {
        $this->htmlTitle = '学生分数录入';
        $classId = $this->get('class_id');
        $subjectId = $this->get('subject_id');
        $resultGradeId = $this->get('result_grade_id');
        // 获取班级学生
        $stuParams['isDelete'] = 0;
        $stuParams['classId'] = $classId;
        // // 按学号排序
        // $stuParams['orderBy'] = 'username ASC';
        // 按座位号排序
        $stuParams['orderBy'] = 'seat_no ASC';

        $studentList = $this->schoolModel->get_student_list($stuParams);
        // 获取班级成绩
        $resultParams['resultGradeId'] = $resultGradeId;
        $resultParams['classId'] = $classId;
        $resultList = $this->dataModel->get_result_list($resultParams);
        // 使用student_id作为键值
        $resultList = array_value_to_key($resultList, 'student_id');
        foreach($studentList as &$student) {
            if(isset($resultList[$student['id']])) {
                $result = $resultList[$student['id']];
                $valueArr = json_decode($result['value'], true);
                // 使用subject_id作为键值
                $valueArr = array_value_to_key($valueArr, 'subject_id');
                if(isset($valueArr[$subjectId])) {
                    $student['score'] = $valueArr[$subjectId]['score'];
                }
            }
        }
        // 按座位号排序（暂时按学号）
        // $timeKey =  array_column($studentList, 'seat_no');
        // array_multisort($timeKey, SORT_ASC, $studentList);
        $this->studentList = $studentList;
        $this->subjectInfo = $this->schoolModel->get_lesson_info($subjectId);
        $this->resultGradeId = $resultGradeId;
        $this->classId = $classId;
        $resultGradeInfo = $this->dataModel->get_result_grade_info($resultGradeId);
        $this->majorId = $resultGradeInfo['major_id'];
        // var_export($resultGradeId);exit;
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'import_result');
    }
    // 保存班级成绩
    public function save_class_result_action() {
        $resultGradeId = $this->post('result_grade_id');
        $subjectId = $this->post('subject_id');
        $classId = $this->post('classId');
        $resultDataArr = $this->post('result_arr');
        // 获取科目信息
        $subjectInfo = $this->schoolModel->get_lesson_info($subjectId);

        // 获取年级项下的班级成绩列表
        $resultParams['resultGradeId'] = $resultGradeId;
        $resultParams['classId'] = $classId;
        $resultList = $this->dataModel->get_result_list($resultParams);
        // 使用student_id作为键值
        $resultList = array_value_to_key($resultList, 'student_id');
        $insertBatch = array();
        $updateBatch = array();
        foreach($resultDataArr as $data) {
            // 转换分数格式
            $data['score'] = (float) $data['score'];
            if(isset($resultList[$data['student_id']])) {
                $result = $resultList[$data['student_id']];
                $valueArr = json_decode($result['value'], true);
                $total = 0;
                $isExist = false;
                foreach($valueArr as $key => $item) {
                    if($item['subject_id'] == $subjectId) {
                        $valueArr[$key]['subject_name'] = $subjectInfo['lesson_name'];
                        $valueArr[$key]['score'] = $data['score'];
                        $total += $data['score'];
                        $isExist = true;
                    } else {
                        $total += $item['score'];
                    }
                }
                if(!$isExist) {
                    $valueArr[] = array(
                        'subject_id' => $subjectId,
                        'subject_name' => $subjectInfo['lesson_name'],
                        'score' => $data['score']
                    );
                    $total += $data['score'];
                }
                $value = json_encode($valueArr, JSON_UNESCAPED_UNICODE);
                $updateBatch[] = array(
                    'id' => $result['id'],
                    // 'result_grade_id' => $resultGradeId,
                    // 'student_id' => $data['student_id'],
                    'value' => $value,
                    'total' => $total,
                    'updatetime' => date('Y-m-d H:i:s')
                );
            } else {
                $valueArr = array(
                    array(
                        'subject_id' => $subjectId,
                        'subject_name' => $subjectInfo['lesson_name'],
                        'score' => $data['score']
                    )
                );
                $value = json_encode($valueArr, JSON_UNESCAPED_UNICODE);
                $insertBatch[] = array(
                    'result_grade_id' => $resultGradeId,
                    'student_id' => $data['student_id'],
                    'value' => $value,
                    'total' => $data['score'],
                    'createtime' => date('Y-m-d H:i:s'),
                    'updatetime' => date('Y-m-d H:i:s')
                );
            }
        }
        // 入库
        if($updateBatch) {
            $this->db->update_batch(DataModel::$resultTable, $updateBatch, 'id');
        }
        if($insertBatch) {
            $this->db->insert_batch(DataModel::$resultTable, $insertBatch);
        }
        exit(json('保存成功', true));

    }
    // 发送成绩通知
    public function notify_class_result() {
        $classId = $this->get('class_id');
        $majorId = $this->get('major_id');
        $major = $this->dataModel->get_result_major_info($majorId);
        $majorTitle = $major['title'];
        // 获取班级成绩列表数据
        $resultList = $this->dataModel->get_result_list_by_class_id($majorId, $classId);
        $this->load->library('wxtemplate');
        $url = wx_url('classes/my_result_detail/' . $major['id']);
        if($resultList) {
            $this->load->model('wxUserModel');
            // 截取成100个
            $arr = array_chunk($resultList, 100);
            // echo'<pre>';var_export($arr);exit;
            foreach($arr as $resultArr) {
                $processDataArr = array();
                foreach($resultArr as $result) {
                    // echo'<pre>';var_export($student);exit;
                    $valueArr = json_decode($result['value'], true);
                    $score = '';
                    foreach($valueArr as $value) {
                        if($value['score'] > 0) {
                            $score .= $value['subject_name'] . $value['score'] . '分；';
                        }
                    }
                    // 发送模板消息
                    $data = array(
                        'first' => array(
                            'value' => '您好，收到新的成绩通知：'
                        ),
                        'keyword1' => array(
                            'value' => $result['realname']
                        ),
                        'keyword2' => array(
                            'value' => $majorTitle
                        ),
                        'keyword3' => array(
                            'value' => $score
                        )
                    );
                    array_push($processDataArr, array(
                        'student_id' => $result['student_id'],
                        'data' => $data
                    ));
                }
                $this->db->insert(WxUserModel::$wxTemplateProcessTable, array(
                    'template_id' => WX_TEMPLATE_RESULT_NOTIFY,
                    'type' => 'student',
                    'data' => json_encode($processDataArr, JSON_UNESCAPED_UNICODE),
                    'url' => $url
                ));
            }
        }

        // $processDataArr = array();
        // foreach($resultList as $result) {
        //     $valueArr = json_decode($result['value'], true);
        //     $score = '';
        //     foreach($valueArr as $value) {
        //         $score .= $value['subject_name'] . $value['score'] . '分；';
        //     }
        //     // 发送模板消息
        //     $data = array(
        //         'keyword1' => array(
        //             'value' => $result['realname']
        //         ),
        //         'keyword2' => array(
        //             'value' => $majorTitle
        //         ),
        //         'keyword3' => array(
        //             'value' => $score
        //         )
        //     );

        //     array_push($processDataArr, array(
        //         'student_id' => $result['student_id'],
        //         'data' => $data 
        //     ));
        // }
        // // 后台进程
        // if($processDataArr) {
        //     $this->load->model('wxUserModel');
        //     $this->db->insert(WxUserModel::$wxTemplateProcessTable, array(
        //         'template_id' => WX_TEMPLATE_RESULT_NOTIFY,
        //         'type' => 'student',
        //         'data' => json_encode($processDataArr, JSON_UNESCAPED_UNICODE),
        //         'url' => $url
        //     ));
        // }
        exit(json('发送成绩成功', true));
    }
    // 学生成绩详情
    public function student_result_detail($majorId) {
        $majorInfo = $this->dataModel->get_result_major_info($majorId);
        $this->htmlTitle = $majorInfo['title'];
        $studentId = $this->get('student_id');
        // 获取学生成绩数据
        $result = $this->dataModel->get_result_info_by_major_id($majorId, $studentId);
        // 获取各科科目
        $resultGradeInfo = $this->dataModel->get_result_grade_info($result['result_grade_id']);
        $subjectIdArr = explode(',', $resultGradeInfo['subject_ids']);
        if($result) {
            // 处理value格式
            $valueArr = json_decode($result['value'], true);
            // foreach($valueArr as $key => $item) {
            //     unset($valueArr[$key]['subject_id']);
            // }
            // 没设置分数的科目，设置默认值0
            $valueArr = array_value_to_key($valueArr, 'subject_id');
            foreach($subjectIdArr as $subjectId) {
                if(!isset($valueArr[$subjectId])) {
                    $subjectInfo = $this->schoolModel->get_lesson_info($subjectId);
                    if($subjectInfo) {
                        $valueArr[$subjectId]['subject_id'] = $subjectId;
                        $valueArr[$subjectId]['subject_name'] = $subjectInfo['lesson_name'];
                        $valueArr[$subjectId]['score'] = 0;
                    }
                }
            }
            $result['value'] = $valueArr;
            // echo'<pre>';var_export($valueArr);exit;
            // 处理total格式
            if(strstr($result['total'], '.0')) {
                $result['total'] = explode('.', $result['total'])[0];
            }
            // 判断是否显示年级排名
            if($result['show_grade_rank']) {
                // 获取年级所有成绩
                $gradeResultList = $this->dataModel->get_result_list(array(
                    'resultGradeId' => $result['result_grade_id'],
                    'isDelete' => 0,
                    'orderBy' => '`total` DESC'
                ));
                foreach($gradeResultList as $key => $item) {
                    $gradeResultList[$key]['rank'] = $key + 1;
                    // 处理并列排名问题
                    $loop = true;
                    $i = 1;
                    while($loop) {
                        if($key - $i >= 0) {
                            if($gradeResultList[$key]['total'] == $gradeResultList[$key - $i]['total']) {
                                $gradeResultList[$key]['rank'] --;
                                $i++;
                            } else {
                                $loop = false;
                            }
                        } else {
                            $loop = false;
                        }
                    }
                    // 各科年级排名
                    $subjectScoreArr = json_decode($item['value'], true);
                    $subjectScoreArr = array_value_to_key($subjectScoreArr, 'subject_id');
                    foreach($subjectIdArr as $subjectId) {
                        if(isset($subjectScoreArr[$subjectId])) {
                            $gradeResultList[$key][$subjectId] = $subjectScoreArr[$subjectId]['score'];
                        } else {
                            $gradeResultList[$key][$subjectId] = 0;
                        }
                    }
                }
                // echo'<pre>';var_export($gradeResultList);exit;
                // 用id作为键值
                $gradeResultList = array_value_to_key($gradeResultList, 'id');
                // 年级总分排名
                $result['grade_rank'] = $gradeResultList[$result['id']]['rank'];
                // 各科年级排名
                $gradeResultListSortArr = array();
                foreach($subjectIdArr as $subjectId) {
                    $timeKey =  array_column($gradeResultList, (int) $subjectId);
                    array_multisort($timeKey, SORT_DESC, $gradeResultList);
                    $gradeResultListSortArr[$subjectId] = $gradeResultList;
                }
                foreach($gradeResultListSortArr as $key => $gradeResultListSort) {
                    foreach($gradeResultListSort as $key2 => $value) {
                        if($value['student_id'] == $studentId) {
                            $rank = $key2 + 1;
                            // 处理并列排名问题
                            $loop = true;
                            $i = 1;
                            while($loop) {
                                if($key2 - $i >= 0) {
                                    if($gradeResultListSort[$key2][$key] == $gradeResultListSort[$key2 - $i][$key]) {
                                        $rank --;
                                        $i++;
                                    } else {
                                        $loop = false;
                                    }
                                } else {
                                    $loop = false;
                                }
                            }
                            $result['suject_id_grade_rank_arr'][$key] = $rank;
                        }
                    }
                }
            }
            // echo'<pre>';var_export($result);exit;
            // 判断是否显示班级排名
            if($result['show_class_rank']) {
                // 获取班级所有成绩
                $classResultList = $this->dataModel->get_result_list(array(
                    'resultGradeId' => $result['result_grade_id'],
                    'classId' => $result['class_id'],
                    'isDelete' => 0,
                    'orderBy' => '`total` DESC'
                ));
                foreach($classResultList as $key => $item) {
                    $classResultList[$key]['rank'] = $key + 1;
                    // 处理并列排名问题
                    $loop = true;
                    $i = 1;
                    while($loop) {
                        if($key - $i >= 0) {
                            if($classResultList[$key]['total'] == $classResultList[$key - $i]['total']) {
                                $classResultList[$key]['rank'] --;
                                $i++;
                            } else {
                                $loop = false;
                            }
                        } else {
                            $loop = false;
                        }
                    }
                    // 各科班级排名
                    $subjectScoreArr = json_decode($item['value'], true);
                    $subjectScoreArr = array_value_to_key($subjectScoreArr, 'subject_id');
                    foreach($subjectIdArr as $subjectId) {
                        if(isset($subjectScoreArr[$subjectId])) {
                            $classResultList[$key][$subjectId] = $subjectScoreArr[$subjectId]['score'];
                        } else {
                            $classResultList[$key][$subjectId] = 0;
                        }
                    }
                }
                // echo'<pre>';var_export($classResultList);exit;
                // 用id作为键值
                $classResultList = array_value_to_key($classResultList, 'id');
                // 班级总分排名
                $result['class_rank'] = $classResultList[$result['id']]['rank'];

                // 各科班级排名
                $classResultListSortArr = array();
                foreach($subjectIdArr as $subjectId) {
                    $timeKey =  array_column($classResultList, (int) $subjectId);
                    array_multisort($timeKey, SORT_DESC, $classResultList);
                    $classResultListSortArr[$subjectId] = $classResultList;
                }
                foreach($classResultListSortArr as $key => $classResultListSort) {
                    foreach($classResultListSort as $key2 => $value) {
                        if($value['student_id'] == $studentId) {
                            $rank = $key2 + 1;
                            // 处理并列排名问题
                            $loop = true;
                            $i = 1;
                            while($loop) {
                                if($key2 - $i >= 0) {
                                    if($classResultListSort[$key2][$key] == $classResultListSort[$key2 - $i][$key]) {
                                        $rank --;
                                        $i++;
                                    } else {
                                        $loop = false;
                                    }
                                } else {
                                    $loop = false;
                                }
                            }
                            $result['suject_id_class_rank_arr'][$key] = $rank;
                        }
                    }
                }
            }

            unset($result['show_grade_rank']);
            unset($result['show_class_rank']);
            unset($result['updatetime']);
            unset($result['is_delete']);
            unset($result['result_grade_id']);
        }
        $this->result = $result;
        $this->studentDetail = true;
        // var_export($result);exit;
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'my_result_detail');
    }

    /*
     * 德育动态列表页面
    */
    public function moral_timeline() {
        $this->htmlTitle = '德育动态';
        // 获取动态栏目列表
        $subjectParams['schoolId'] = $this->user['school_id'];
        if(isset($this->user['campus_id'])) {
            $subjectParams['campusId'] = $this->user['campus_id'];
        }
        $subjectParams['isDelete'] = 0;
        $subjectList = $this->contentModel->get_moral_timeline_subject_list($subjectParams);
        // 获取前4个
        if(count($subjectList) > 4) {
            $this->defaultSubjectList = array_slice($subjectList, 0, 4);
        } else {
            $this->defaultSubjectList = $subjectList;
        }
        $this->subjectList = $subjectList;
        $this->subjectCount = count($subjectList);
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'moral_timeline');
    }

    // 获取德育动态列表
    public function get_moral_timeline_list() {
        // 获取动态栏目列表
        $subjectParams['schoolId'] = $this->user['school_id'];
        if(isset($this->user['campus_id'])) {
            $subjectParams['campusId'] = $this->user['campus_id'];
        }
        $subjectParams['isDelete'] = 0;
        $subjectList = $this->contentModel->get_moral_timeline_subject_list($subjectParams);
        if(empty($this->get('subject')) && empty($subjectList)) {
            exit(json('', true, array()));
        }
        $subjectId = $this->get('subject') ? $this->get('subject') : $subjectList[0]['id'];
        $page = $this->get('page') ? $this->get('page') : 1;
        // 获取动态列表
        $data['pageStart'] = ($page - 1) * 10;
        $data['pageSize']= 10;
        $data['schoolId'] = $this->user['school_id'];
        if(isset($this->user['campus_id'])) {
            $data['campusId'] = $this->user['campus_id'];
        }
        // 过滤软删除
        $data['isDelete'] = 0;
        $data['subjectId'] = $subjectId;
        $timelineList = $this->contentModel->get_moral_timeline_list($data);
        foreach($timelineList as &$timeline) {
            // 处理富文本
            if($timeline['content']) {
                $timeline['content'] = strip_tags($timeline['content']);
            }
            // 处理时间格式
            $timeline['createtime'] = date('Y-m-d', strtotime($timeline['createtime']));
        }
        exit(json('', true, $timelineList));
    }

    // 德育动态详情页面
    public function moral_timeline_detail($id) {
        $this->htmlTitle = '德育动态';
        // 
        $timeline = $this->contentModel->get_moral_timeline_info($id);
        if($timeline['content']) {
            $timeline['content'] = handle_rich_text_img_preview($timeline['content']);
        }
        // 处理时间格式
        $timeline['createtime'] = date('Y-m-d', strtotime($timeline['createtime']));
        $this->timeline = $timeline;
        // 获取jssdk参数
        $this->load->library('wechat');
        $url = substr(BASE_URL, 0 , -1) . $_SERVER['REQUEST_URI'];
        $this->dataJssdk = $this->wechat->jssdk_data($url);
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'moral_timeline_detail');
    }

    /*
     * 德育活动列表页面
    */
    public function moral_activity() {
        $this->load->model('staffModel');
        $this->htmlTitle = '德育活动';
        $remarkParams['schoolId'] = $this->user['school_id'];
        if($this->bindUserType == BIND_TYPE_STUDENT) {
            $params['studentId'] = $pendingParams['studentId'] = $remarkParams['studentId'] = $this->user['id'];
        } else {
            // 获取班主任对应的班级列表
            $coachParams['teacherId'] = $this->user['id'];
            $coachParams['coachType'] = COACH_TYPE_MASTER; 
            $coachList = $this->staffModel->get_coach_list($coachParams);
            if(empty($coachList)) {
                // 该老师不是班主任
                $this->isMaster = 0;
            } else {
                $this->isMaster = 1;
                if(count($coachList) === 1) {
                    // 只有一个班级
                    // $params['classId'] = $pendingParams['classId'] = $remarkParams['classId']  = $coachList[0]['class_id'];
                    $params['classSet'] = $pendingParams['classSet'] = $remarkParams['classSet']  = $coachList[0]['class_ids'];
                } else {
                    $params['classSet'] = $pendingParams['classSet'] = $remarkParams['classSet'] = array_value_implode($coachList, "class_ids");
                }
            }
        }
        $params['isDelete'] = $pendingParams['isDelete'] = $remarkParams['isDelete'] = 0;
        // 获取已审核列表
        $params['excludePending'] = MORAL_PENDING;
        $excludePendingList = $this->contentModel->get_moral_activity_list($params);

        // 获取未审核列表
        $pendingParams['state'] = MORAL_PENDING;
        $pendingList = $this->contentModel->get_moral_activity_list($pendingParams);
        foreach($pendingList as &$activity) {
            // 获取审核状态
            $activity['stateFormat'] = transform_activity_state($activity['state']);
        }
        foreach($excludePendingList as &$activity) {
            // 获取审核状态
            $activity['stateFormat'] = transform_activity_state($activity['state']);
        }
        // 评价列表
        $remarkList = $this->contentModel->get_moral_remark_list($remarkParams);
        if($remarkList) {
            // 获取评价结果列表
            $resultParams['schoolId'] = $this->user['school_id'];
            $resultParams['isDelete'] = 0;
            $resultList = $this->contentModel->get_moral_remark_result_list($resultParams);
            $resultList = array_value_to_key($resultList, 'id');
            foreach($remarkList as &$remark) {
                // 获取评价结果名称
                $remark['result_title'] = $resultList[$remark['result_id']]['title'];
                // // 获取材料图片
                // if($remark['material']) {
                //     $remark['imgArr'] = explode(',', $remark['material']);
                // } else {
                //     $remark['imgArr'] = array();
                // }
                // 处理富文本
                if($remark['content']) {
                    $remark['content'] = strip_tags($remark['content']);
                }
            }
        }

        $this->pendingList = $pendingList;
        $this->excludePendingList = $excludePendingList;
        $this->remarkList = $remarkList;
        // var_export($excludePendingList);exit;
        // var_export($remarkList);exit;

        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'moral_activity');
    }

    // 德育活动详情页面
    public function moral_activity_detail($id) {
        $this->htmlTitle = '德育活动详情';
        $activity = $this->contentModel->get_moral_activity_info($id);
        // 获取审核状态
        $activity['stateFormat'] = transform_activity_state($activity['state']);
        // 获取学生信息
        $student = $this->schoolModel->get_student_info($activity['student_id']);
        // 获取评价老师名称
        if($activity['remark_user_id']) {
            $teacher = $this->schoolModel->get_teacher_info($activity['remark_user_id']);
            $activity['teacher_realname'] = $teacher['realname'];
        }
        $activity['student'] = $student;
        // 获取材料图片
        $activity['imgArr'] = $this->_get_img_arr($activity['material']);
        $this->activity = $activity;
        // var_export($activity);exit;
        // 获取jssdk参数
        $this->load->library('wechat');
        $url = substr(BASE_URL, 0 , -1) . $_SERVER['REQUEST_URI'];
        $this->dataJssdk = $this->wechat->jssdk_data($url);
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'moral_activity_detail');
    }

    // 德育评价详情页面
    public function moral_remark_detail($id) {
        $this->htmlTitle = '德育评价详情';
        $remark = $this->contentModel->get_moral_remark_info($id);
        // 获取评价结果标题
        $result = $this->contentModel->get_moral_remark_result_info($remark['result_id']);
        $remark['result_title'] = $result['title'];
        // 获取材料图片
        if($remark['material']) {
            $remark['imgArr'] = explode(',', $remark['material']);
        } else {
            $remark['imgArr'] = array();
        }
        // 获取学生信息
        $student = $this->schoolModel->get_student_info($remark['student_id']);
        $remark['student'] = $student;
        $this->remark = $remark;
        // var_export($remark);exit;
        // 获取jssdk参数
        $this->load->library('wechat');
        $url = substr(BASE_URL, 0 , -1) . $_SERVER['REQUEST_URI'];
        $this->dataJssdk = $this->wechat->jssdk_data($url);
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'moral_remark_detail');
    }

    // 删除德育活动
    public function delete_activity_action() {
        $id = $this->post('id');
        $data = array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->update(ContentModel::$moralActivityTable, $data, array('id' => $id));
        exit(json('删除成功', true));
    }
    // 通过德育活动审核
    public function accept_activity_action() {
        $id = $this->post('id');
        $remark = trim($this->post('remark'));
        $data = array(
            'remark_user_id' => $this->user['id'],
            'state' => MORAL_ACCEPTED,
            'remark' => $remark,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->update(ContentModel::$moralActivityTable, $data, array('id' => $id));
        exit(json('通过成功', true));
    }
    // 拒绝德育活动审核
    public function reject_activity_action() {
        $id = $this->post('id');
        $data = array(
            'remark_user_id' => $this->user['id'],
            'state' => MORAL_REJECTED,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->update(ContentModel::$moralActivityTable, $data, array('id' => $id));
        exit(json('拒绝成功', true));
    }

    // 编辑德育活动页面
    public function moral_activity_edit($id=0) {
        $this->htmlTitle = '编辑德育活动';
        if($id) {
            $activity = $this->contentModel->get_moral_activity_info($id);
            // 获取审核状态
            $activity['stateFormat'] = transform_activity_state($activity['state']);
            // 活动时间去掉秒
            $activity['act_time'] = time_remove_second($activity['act_time']);
            // 获取材料图片
            $activity['imgArr'] = $this->_get_img_arr($activity['material']);
            $this->activity = $activity;
        }
        // 获取jssdk参数
        $this->load->library('wechat');
        $url = substr(BASE_URL, 0 , -1) . $_SERVER['REQUEST_URI'];
        $this->dataJssdk = $this->wechat->jssdk_data($url);
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'moral_activity_edit');
    }

    // 保存德育活动
	public function save_activity_action() {
        $activityId = $this->post("id");
        $studentId = $this->user['id'];
        $actTime = $this->post("act_time");
        $duration = $this->post("duration");
        $mode = $this->post('mode') ? $this->post('mode') : '';
        $dest = $this->post('dest') ? $this->post('dest') : '';
        $content = $this->post('content') ? $this->post('content') : '';
        $harvest = $this->post('harvest') ? $this->post('harvest') : '';
        $materialArr = $this->post('material');
        // var_export($material);exit;
        // 参数检查
        if(!$actTime) throw new Exception("请选择活动时间");
        if(!$mode) throw new Exception("请填写活动方式");
        if(!$duration) throw new Exception("请填写活动时长");
        if(!is_numeric($duration)) throw new Exception("活动时长必须为数字");
        if(!$dest) throw new Exception("请填写活动地点");
        if(!$content) throw new Exception("请填写活动内容");
        if(!$harvest) throw new Exception("请填写活动收获");

        if($actTime) {
            $pattern = '/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/';
            preg_match($pattern, $actTime, $match);
            if($match) {
                $actTime .= ':00';
            }
        }

        if($materialArr) {
            if(9 < count($materialArr)) {
                throw new Exception("最多只能上传9张图片");
            }
            $material = implode(',', $materialArr);
        } else {
            $material = '';
        }
        // 提示信息
        $msg = $activityId ? '修改活动成功' : '新增活动成功';
        // 入库
        $data['student_id'] = $studentId;
        $data['act_time'] = $actTime;
        $data['duration'] = $duration;
        $data['mode'] = $mode;
        $data['dest'] = $dest;
        $data['content'] = $content;
        $data['harvest'] = $harvest;
        $data['material'] = $material;
        $data['updatetime'] = date("Y-m-d H:i:s");
        if($activityId) {
            $this->db->update(ContentModel::$moralActivityTable, $data, "id='{$activityId}'");
        } else {
            $data['school_id'] = $this->user['school_id'];
            $data['campus_id'] = $this->user['campus_id'];
            $data['is_delete'] = 0;
            $data['createtime'] = $data['updatetime'];
            $data['state'] = MORAL_PENDING;
            $data['is_self'] = 1;
            $this->db->insert(ContentModel::$moralActivityTable, $data);
            // 发送模板消息通知学生
        }
        // 返回值
        exit(json($msg, true));
    }

    // 班级相册页面
    public function album() {
        $this->htmlTitle = '班级相册';
        // 任课班级
        $this->teacherClassArr = array();
        if($this->bindUserType == BIND_TYPE_TEACHER) {
            // 教师权限
            $this->teacherClassArr = $this->get_classes_by_teacher_id();
        }
        // 获取jssdk参数
        $this->load->library('wechat');
        $url = substr(BASE_URL, 0 , -1) . $_SERVER['REQUEST_URI'];
        $this->dataJssdk = $this->wechat->jssdk_data($url);
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'album');
    }

    // 获取相册列表
    public function get_album_list() {
        $pageStart = $this->get('pageStart');
        $pageSize = $this->get('pageSize');
        $params['isDelete'] = 0;
        $params['pageStart'] = !empty($pageStart) ? $pageStart : 0;
        $params['pageSize'] = !empty($pageSize) ? $pageSize : 10;
        if($this->bindUserType == BIND_TYPE_STUDENT) {
            // 当前角色为学生
            if(isset($this->user['class'])) {
                $params['classId'] = $this->user['class']['id'];
            } else {
                $params['classId'] = 0;
            }
        } else {
            $teacherClassArr = $this->get_classes_by_teacher_id();
            if($this->get('class_id')) {
                $params['classId'] = $this->get('class_id');
            } else {
                $params['classId'] = $teacherClassArr ? $teacherClassArr[0]['id'] : 0;
            }
        
        }
        // 获取相册分类
        $albumCategoryList = $this->contentModel->get_album_category($params);
        // 获取相册内容
        foreach($albumCategoryList as &$category) {
            // 获取相册内容
            $albumParams['categoryId'] = $category['id'];
            $category['album'] = $this->contentModel->get_album($albumParams);
        }
        // echo '<pre>';var_export($albumCategoryList);exit;

        foreach($albumCategoryList as &$homework) {
           
        }
        exit(json('', true, $albumCategoryList));
    }
    // 保存相册分类
    public function save_category_action(){
        $categoryId = $this->post("id");
        $classId = $this->post("class_id");

        $categoryName = trim($this->post("category_name"));
        // 获取班级信息
        $classInfo = $this->classesModel->get_class_info($classId);
        if(!$classInfo) throw new Exception("参数错误");
        // 参数检查
        if(!$categoryName) throw new Exception("请填写相册分类名称");
        // 入库
        $data['album_category_name'] = $categoryName;
        $data['updatetime'] = date("Y-m-d H:i:s");
        if($categoryId) {
            $this->db->update(ContentModel::$albumCategoryTable, $data, "id='{$categoryId}'");
        } else {
            $data['school_id'] = $classInfo['school_id'];
            $data['campus_id'] = $classInfo['campus_id'];
            $data['class_id'] = $classId;
            $data['createtime'] = $data['updatetime'];
            $this->db->insert(ContentModel::$albumCategoryTable, $data);
        }
        // 返回值
        $msg = $categoryId ? '修改分类成功' : '添加分类成功';
        exit(json($msg, true));
    }
    // 保存相册图片
    public function save_image_action(){
        $imageId = $this->post('id');
        $classId = $this->post("class_id");
        $categoryId = $this->post("category_id");
        $imageLink = $this->post("image_link");
        $imageTitle = $this->post("image_title") ? $this->post("image_title") : '';
        if(empty($imageId)) {
            // 参数检查
            if(!$classId || !$categoryId) throw new Exception("参数错误");
        }

        // if(!$imageTitle) throw new Exception("请填写图片标题");
        if(!$imageLink) throw new Exception("请上传图片");
        // 获取班级信息
        $classInfo = $this->classesModel->get_class_info($classId);
        // 入库
        $data['image_link'] = $imageLink;
        $data['image_desc'] = $imageTitle;
        $data['image_recommend'] = $this->post("image_recommend") ? $this->post("image_recommend") : 0;
        $data['image_sort'] = $this->post("image_sort") ? $this->post("image_sort") : 0;
        $data['updatetime'] = date("Y-m-d H:i:s");
        if($imageId) {
            $this->db->update(ContentModel::$albumTable, $data, "id='{$imageId}'");
            $msg = '修改图片成功';
        } else {
            $data['school_id'] = $classInfo['school_id'];
            $data['campus_id'] = $classInfo['campus_id'];
            $data['class_id'] = $classId;
            $data['category_id'] = $categoryId;
            $data['createtime'] = $data['updatetime'];
            $this->db->insert(ContentModel::$albumTable, $data);
            $imageId = $this->db->insert_id();
            $msg = '新增图片成功';
        }
        exit(json($msg, true, array(
            'id' => $imageId
        )));
    }
    // 删除相册图片
    public function delete_album_image(){
        $imageId = $this->post("id");
        if(empty($imageId)) throw new Exception("参数错误");
        $imageInfo = $this->contentModel->get_album_image_info($imageId);
        if($this->bindUserType != BIND_TYPE_TEACHER || !$imageInfo || $imageInfo['school_id'] !=  $this->user['school_id']) throw new Exception("删除失败，请刷新后重试");
        // 删除图片
        $this->db->update(ContentModel::$albumTable, array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        ), "`id`='{$imageId}'");
        exit(json("删除成功", true));
    }
    // 删除相册分类
    public function delete_album_category(){
        $categoryId = $this->post("id");
        if(empty($categoryId)) throw new Exception("参数错误");
        $categoryInfo = $this->contentModel->get_album_category_info($categoryId);
        if($this->bindUserType != BIND_TYPE_TEACHER || !$categoryInfo || $categoryInfo['school_id'] != $this->user['school_id']) throw new Exception("删除失败，请刷新后重试");
        // 删除分类下的相册
        $this->db->update(ContentModel::$albumTable, array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        ), "`category_id`='{$categoryId}'");
        // 删除分类
        $this->db->update(ContentModel::$albumCategoryTable, array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        ), "`id`='{$categoryId}'");
        exit(json("删除成功", true));
    }
    // 设置相册首页推荐
    public function update_album_recommend(){
        $id = $this->post("id");
        $recommend = $this->post("recommend");
        $this->db->update(ContentModel::$albumTable, array(
            'image_recommend' => $recommend,
            'updatetime' => date('Y-m-d H:i:s')
        ), "`id`='{$id}'");
        $msg = $recommend ? '设置推荐成功' : '取消推荐成功';
        exit(json($msg, true));
    }

    // 数据统计页面
    public function statistics(){
        $this->htmlTitle = '数据统计';
        // 默认本周日期
        $thisWeekDateArr = get_this_week_date();
                // echo '<pre>';var_export($thisWeekDateArr);exit;
        $dateArr['begin_date'] = $thisWeekDateArr[0];
        $dateArr['end_date'] = $thisWeekDateArr[count($thisWeekDateArr) - 1];
      
        $this->dateArr = $dateArr;



        // 任课班级
        $this->teacherClassArr = $this->get_classes_by_teacher_id();
        $classlist = $this->get_classes_by_teacher_id();

        // 获取全校考勤情况
        $this->schoolSignData = $this->_get_school_sign_data();
        // $classlist = [];
        if($classlist) {
            $classnameArr = array();
            $signArr = array();
            $notSignArr = array();
            foreach($classlist as $class) {
                $data = $this->_get_class_sign_data($class['id']);
                array_push($classnameArr, $class['class_name']);
                array_push($signArr, $data['signCount']);
                array_push($notSignArr, $data['notSignCount']);
            }
            $this->classnameJson = json_encode($classnameArr, JSON_UNESCAPED_UNICODE);
            $this->classSignJson = json_encode($signArr, JSON_UNESCAPED_UNICODE);
            $this->classNotSignJson = json_encode($notSignArr, JSON_UNESCAPED_UNICODE);
            $this->classCount = count($classlist);
            // 计算柱形图高度
            if($this->classCount === 1) {
                $barEchartHeight = '1.2rem';
            } elseif($this->classCount === 2) {
                $barEchartHeight = '1.8rem';
            } elseif($this->classCount === 3) {
                $barEchartHeight = '2.2rem';
            } elseif($this->classCount < 8) {
                $barEchartHeight =  0.6 * $this->classCount . 'rem';
            }  else {
                $barEchartHeight =  0.42 * $this->classCount . 'rem'; 
            }
            $this->barEchartHeight = $barEchartHeight;
            // echo'';var_export($this->teacherClassArr);exit;
        } else {
            $this->classCount = 0;
        }

        // 判断是否学校管理员
        // 获取学校管理员对应的年级列表
        $isSchoolAdmin = false;
        if($this->user['user_type'] == USER_TYPE_SCHOOL) {
            $isSchoolAdmin = true;
        } else {
            $coachParams['teacherId'] = $this->user['id'];
            $coachParams['coachType'] = COACH_TYPE_SCHOOL_ADMIN; 
            $schoolAdminCoachList = $this->staffModel->get_coach_list($coachParams);
            if($schoolAdminCoachList) {
                $isSchoolAdmin = true;
            }
        }
        $this->isSchoolAdmin = $isSchoolAdmin;

        // 获取学校作息
        $scheduleParams['schoolId'] = $this->user['school_id'];
        // 只取本周的
        $scheduleParams['isThisWeek'] = 1;
        $scheduleList = $this->classesModel->get_school_schedule($scheduleParams);
        // 获取第一项即可
        $scheduleInfo = $scheduleList[0];
        $timeArr = json_decode($scheduleInfo['schedule_time_json'], true);        
        $classIndex = $this->dataModel->get_class_index($timeArr, date('Y-m-d'));
        // $classIndex = 1;
        // 支持早读，晚间
        $timeslotPrefixArr = array();
        if($scheduleInfo['schedule_early_morning_number'] > 0) {
            for($i = 0;$i < $scheduleInfo['schedule_early_morning_number'];$i++) {
                $tmpIndex = $i + 1;
                $timeslotPrefixArr[] = '早间' . $tmpIndex;
            }
        }
        $dayScheduleNum = $scheduleInfo['schedule_morning_number'] + $scheduleInfo['schedule_afternoon_number'];
        for($i = 0;$i < $dayScheduleNum;$i++) {
            $tmpIndex = $i + 1;
            $timeslotPrefixArr[] = '第' . $tmpIndex . '节';
        }
        if($scheduleInfo['schedule_night_number'] > 0) {
            for($i = 0;$i < $scheduleInfo['schedule_night_number'];$i++) {
                $tmpIndex = $i + 1;
                $timeslotPrefixArr[] = '晚间' . $tmpIndex;
            }
        }

        // 第几节
        $timeslot = $this->get('timeslot');
        $timeslotArr = array();
        // 当天也显示全部节数
        for($i = 1; $i <= count($timeArr); $i++) {
            $lessonTime = $timeArr[$i - 1];
            $lessonBeginTime = $lessonTime['beginTime'];
            $lessonEndTime = date('H:i', strtotime($lessonTime['beginTime']) + $lessonTime['duration'] * 60);
            if(isset($timeslotPrefixArr[$i - 1])) {
                $prefix = $timeslotPrefixArr[$i - 1];
            } else {
                $prefix = '';
            }
            $v = $prefix . '（' . $lessonBeginTime . '-' . $lessonEndTime . '）';

            array_push($timeslotArr, $v);
        }
        if($timeslot) {
            $classIndex = $timeslot;
        }
        $this->classIndex = $classIndex;
        $this->timeslotArr = $timeslotArr;
        $this->timeslotPrefixArr = $timeslotPrefixArr;
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'statistics/statistics');
    }

    // 获取班级考勤情况折线图数据
    public function get_class_sign_data() {
        $classId = $this->get('class_id');
        $beginDate = $this->get('begin_date');
        $endDate = $this->get('end_date');
        if(empty($classId) || empty($beginDate) || empty($beginDate)) {
            throw new Exception('参数错误');
        }
        if($beginDate > $endDate) {
            throw new Exception('开始日期不能大于结束日期');
        }
        if($beginDate < $endDate) {
            $dateCount = count(getDateFromRange($beginDate, $endDate));
            if($dateCount > 32) {
                throw new Exception('考勤时段不能超过一个月');
            }
        }
        // 节数
        $timeslot = $this->get('timeslot');
        
        $classInfo = $this->classesModel->get_class_info($classId);
		// 获取某班每周的上课天数
        $weekArr = $this->classesModel->get_class_schedule_week_arr($classInfo);
        // 获取日期区间
        $dateArr = $this->classesModel->get_date_arr_and_filter_week($beginDate, $endDate, $weekArr);
        // 转换日期格式为07/10\n2021
        $dateFormatArr = array();
        foreach($dateArr as $value) {
            $arr = explode('-', $value);
            $dateFormatArr[] = $arr[1] . '/' . $arr[2] . "\n" . $arr[0];
        }
        // 计算考勤次数
        $signParams['schoolId'] = $classInfo['school_id'];
        $signParams['campusId'] = $classInfo['campus_id'];
        $signParams['classId'] = $classInfo['id'];
        $signParams['begindate'] = $beginDate;
        $signParams['enddate'] = $endDate;
        // 只获取上课签到，排除闸机，一体机签到
        $signParams['onlySignForClass'] = 1;
        // 只获取重新签到
        $signParams['isRefreshSign'] = 1;
        // 节数
        if($timeslot) {
            $signParams['scheduleClassIndexSet'] = $timeslot;
        }

        $signArr = $this->dataModel->get_student_sign_list($signParams);
        // 考勤人数
        $signNumArr = array();
        // 迟到人数
        $lateNumArr = array();
        // 缺勤人数
        // 计算考勤和迟到人数
        foreach($signArr as $sign) {
            if($sign['is_supplement'] == 1) {
                if(isset($lateNumArr[$sign['sign_date']])) {
                    $lateNumArr[$sign['sign_date']] ++;
                } else {
                    $lateNumArr[$sign['sign_date']] = 1;
                }
            } else {
                if(isset($signNumArr[$sign['sign_date']])) {
                    $signNumArr[$sign['sign_date']] ++;
                } else {
                    $signNumArr[$sign['sign_date']] = 1;
                }
            }    
        }
        // 计算缺勤人数
        // 获取全班人数
        $studentParams['schoolId'] = $classInfo['school_id'];
        $studentParams['campusId'] = $classInfo['campus_id'];
        $studentParams['classId'] = $classInfo['id'];
        $studentParams['isDelete'] = 0;
        $studentParams['getRowNumber'] = 1;
        $studentCount = $this->schoolModel->get_student_list($studentParams);
        // 使用sign_date和student_id作为键值
        $signArrUnique = array_value_to_key_with_underline($signArr, 'sign_date,student_id');
        $absenceTmpArr = array();
        foreach($signArrUnique as $key => $value) {
            // 通过键值获取sign_date和student_id
            $arr = explode('_', $key);
            $signDate = $arr[0];
            $studentId = $arr[1];
            $absenceTmpArr[$signDate][] = $studentId;
        }
        $signDataArr = array();
        $lateDataArr = array();
        $absenceDataArr = array();
        foreach($dateArr as $date) {
            // 考勤人数
            if(isset($signNumArr[$date])) {
                $signDataArr[] = $signNumArr[$date];
            } else {
                $signDataArr[] = 0;
            }
            // 迟到人数
            if(isset($lateNumArr[$date])) {
                $lateDataArr[] = $lateNumArr[$date];
            } else {
                $lateDataArr[] = 0;
            }
            // 缺勤人数
            if(isset($absenceTmpArr[$date])) {
                $res = $studentCount - count($absenceTmpArr[$date]);
                $absenceDataArr[] = $res > 0 ? $res : 0;
            } else {
                $absenceDataArr[] = $studentCount;
            }
        }

        // var_export(isset($signNumArr['2021-08-21']));var_export($signNumArr['2021-08-21']);exit;
        // exit(json('', true, $absenceTmpArr));
        // $dataArr = array(
        //     'date' => ["07/10\n2021", '07/10\n2021','08/10\n2021','09/10\n2021','06/10\n2021','06/10\n2021', '06/10\n2021','06/10\n2021','06/10\n2021','06/10\n2021','06/10\n2021', '06/10\n2021','06/10\n2021','06/10\n2021','06/10\n2021'],
        //     'sign' => [1200, 1321, 101, 134, 90, 230, 210,120, 132, 101, 134, 90, 230, 210,120, 132, 101, 134, 90, 230, 210],
        //     'absence' => [120, 121, 101, 134, 90, 230, 210,120, 132, 101, 134, 90, 230, 210,120, 132, 101, 134, 90, 230, 210],
        //     'late' => [20, 21, 101, 134, 90, 230, 210,120, 132, 101, 134, 90, 230, 210,120, 132, 101, 134, 90, 230, 210],
        // );
        $dataArr = array(
            'date' => $dateFormatArr,
            'sign' => $signDataArr,
            'late' => $lateDataArr,
            'absence' => $absenceDataArr,
        );

        exit(json('', true, $dataArr));
    }

    // 班级视频页面
    public function video() {
        $this->htmlTitle = '班级视频';
        // 任课班级
        $this->teacherClassArr = array();
        if($this->bindUserType == BIND_TYPE_TEACHER) {
            // 教师权限
            $this->teacherClassArr = $this->get_classes_by_teacher_id();
        }
        // 生成又拍云签名
        require_once('vendor/autoload.php');
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $serviceConfig->setFormApiKey(UP_FORM_API);
        $serviceConfig->getImageUploadParams(UP_FILEPATH, $this->policy, $this->signature);
        
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR . 'video');
    }

    // 获取视频列表
    public function get_video_list() {
        $pageStart = $this->get('pageStart');
        $pageSize = $this->get('pageSize');
        $params['isDelete'] = 0;
        // 获取全部
        // $params['pageStart'] = !empty($pageStart) ? $pageStart : 0;
        // $params['pageSize'] = !empty($pageSize) ? $pageSize : 10;
        if($this->bindUserType == BIND_TYPE_STUDENT) {
            // 当前角色为学生
            if(isset($this->user['class'])) {
                $params['classId'] = $this->user['class']['id'];
            } else {
                $params['classId'] = 0;
            }

            // 过滤视频为空的
            $params['notEmpty'] = 1;
        } else {
            $teacherClassArr = $this->get_classes_by_teacher_id();
            if($this->get('class_id')) {
                $params['classId'] = $this->get('class_id');
            } else {
                $params['classId'] = $teacherClassArr ? $teacherClassArr[0]['id'] : 0;
            }
        
        }
        // 获取视频分类
        $videoList = $this->contentModel->get_video_list($params);

        if($videoList) {
            // 判断第一条视频压缩是否完成
            // 加载又拍云sdk
            require_once('vendor/autoload.php');
            // 初始化又拍云接口
            $config = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
            $upyun = new Upyun\Upyun($config);

            // 判断最新一条视频是否压缩完成
            if($videoList[0]['video_old_link']) {
                // 电脑上传的
                $linkUpyun = str_replace(UP_URL, '', $videoList[0]['video_link']);
                if(!$upyun->has($linkUpyun)) {
                    $videoList[0]['video_link'] =  isset($videoList[0]['video_old_link']) && $videoList[0]['video_old_link'] ? $videoList[0]['video_old_link'] : '';
                }
            }
        }

        exit(json('', true, $videoList));
    }

    // 保存视频图片
    public function save_video_title_action(){
        $videoId = $this->post('id');
        $classId = trim($this->post("class_id"));
        $videoTitle = trim($this->post("title"));

        if(!$videoTitle) throw new Exception("请填写视频标题");
        // 获取班级信息
        $classInfo = $this->classesModel->get_class_info($classId);
        // 入库
        $data['user_id'] = $this->user['id'];
        $data['video_title'] = $videoTitle;
        $data['updatetime'] = date("Y-m-d H:i:s");
        if($videoId) {
            $this->db->update(ContentModel::$videoTable, $data, "id='{$videoId}'");
            $msg = '修改标题成功';
        } else {
            $data['school_id'] = $classInfo['school_id'];
            $data['campus_id'] = $classInfo['campus_id'];
            $data['class_id'] = $classId;
            $data['createtime'] = $data['updatetime'];
            $this->db->insert(ContentModel::$videoTable, $data);
            $videoId = $this->db->insert_id();
            $msg = '新增标题成功';
        }
        exit(json($msg, true, array(
            'id' => $videoId
        )));
    }

    // 保存视频
    public function save_video_action(){
        $id = $this->post('id');
        // var_export($id);exit;
        $videoOldLink = $this->post("video_old_link");
        $videoLink = $this->post("video_link");
        $videoPoster = $this->post("video_poster");
        // 入库
        $data['video_old_link'] = $videoOldLink;
        $data['video_link'] = $videoLink;
        $data['video_poster'] = $videoPoster;
        $data['updatetime'] = date("Y-m-d H:i:s");

        $this->db->update(ContentModel::$videoTable, $data, "id='{$id}'");
        $msg = '上传视频成功';
       
        exit(json($msg, true, array(
            'id' => $id
        )));
    }
    // 删除视频
    public function delete_video_action(){
        $id = $this->post("id");
        if(empty($id)) throw new Exception("参数错误");
        $videoInfo = $this->contentModel->get_video_info($id);
        if($this->bindUserType != BIND_TYPE_TEACHER || !$videoInfo || $videoInfo['school_id'] !=  $this->user['school_id']) throw new Exception("删除失败，请刷新后重试");
        
        // 判断视频是否对应多个班级
        if(strstr($videoInfo['class_id'], ',')) {
            $classIdArr = explode(',', $videoInfo['class_id']);
            $classId = $this->post('class_id');
            $key = array_search($classId ,$classIdArr);
            array_splice($classIdArr, $key, 1);
            $classIdStr = implode(',', $classIdArr);
            // 删除班级视频
            $this->db->update(ContentModel::$videoTable, array(
                'class_id' => $classIdStr,
                'updatetime' => date('Y-m-d H:i:s')
            ), "`id`='{$id}'");
        } else {
            // 删除班级视频
            $this->db->update(ContentModel::$videoTable, array(
                'is_delete' => 1,
                'updatetime' => date('Y-m-d H:i:s')
            ), "`id`='{$id}'");
        }

        exit(json("删除成功", true));
    }


    // 获取当天全校考勤情况
    private function _get_school_sign_data() {
        $data= array();
        //获取学校所有人数
        $params['schoolId'] = $this->user['school_id'];
        $params['getRowNumber'] = true;
        $params['isDelete'] = 0;
        $params['date'] = date('Y-m-d');
        $data['studentNum'] = $this->schoolModel->get_student_list($params);
        //获取今天已到人数，已弃用，请求太久
        // $signData = $this->dataModel->get_school_sign_data($params['date'], $params['schoolId']);
        // 获取之前最近的重新签到课程，包含本节课
        $schduleParams['schoolId'] = $this->user['school_id'];
        $schduleParams['isThisWeek'] = 1;
        $scheduleInfo = $this->classesModel->get_school_schedule_row($schduleParams);
        $timeArr = json_decode($scheduleInfo['schedule_time_json'], true);
        // 之前日期的考勤按最后一节情况
        $refreshClassIndex = $this->dataModel->get_refresh_class_index($timeArr, $params['date']);
        // foreach($signData as &$item) {
        //     if($item['sign_id']) {
        //         if($item['state'] == SIGN_STATE_LEAVE) {
        //             // 离校
        //             $item['sign_id'] = 0;
        //         } else {
        //             if($item['schedule_class_index'] < $refreshClassIndex) {
        //                 // 重新签到后还没签
        //                 $item['sign_id'] = 0;
        //             }
        //         }
        //     }
        // }

        // $data['dateSignNum'] = 0;
        // // 计算签到个数
        // foreach($signData as $item2) {
        //     if($item2['sign_id']) {
        //         $data['dateSignNum'] ++;
        //     }
        // }

        // 获取该学校默认校区
        $campusParams['schoolId'] = $params['schoolId'];
        $campusList = $this->schoolModel->get_campus_list($campusParams);
        $campusId = 0;
        foreach($campusList as $campus) {
            if($campus['campus_name'] === '默认校区') {
                $campusId = $campus['id'];
                break;
            }
        }
        // 如找不到默认校区，获取第一个校区
        $campusId = $campusId ? $campusId : $campusList[0]['id'];
        $data['dateSignNum'] = $this->dataModel->get_school_sign_data_count($params['date'], $params['schoolId'], $campusId, $refreshClassIndex);
        //获取今天未到人数
        $data['dateNotSignNum'] = $data['studentNum'] - $data['dateSignNum'];
        if ($data['dateNotSignNum'] < 0) {
            $data['dateNotSignNum'] = 0;
        }

        // echo'<pre>';var_export($data);exit;
        return $data;
    }

    // 获取当天班级考勤情况
    private function _get_class_sign_data($classId) {
        $date = date("Y-m-d");

        $classInfo = $this->classesModel->get_class_info($classId);

        // 获取考勤数据（已弃用，请求太久）
        // $signData = $this->dataModel->get_sign_data($classInfo, $date);
        // 获取之前最近的重新签到课程，包含本节课
        $schduleParams['schoolId'] = $this->user['school_id'];
        $schduleParams['isThisWeek'] = 1;
        $scheduleInfo = $this->classesModel->get_school_schedule_row($schduleParams);
        $timeArr = json_decode($scheduleInfo['schedule_time_json'], true);
        // 之前日期的考勤按最后一节情况
        $refreshClassIndex = $this->dataModel->get_refresh_class_index($timeArr, $date);
        // foreach($signData as &$item) {
        //     if($item['sign_id']) {
        //         if($item['state'] == SIGN_STATE_LEAVE) {
        //             // 离校
        //             $item['sign_id'] = 0;
        //         } else {
        //             // var_export($classIndex);exit;
        //             if($item['schedule_class_index'] < $refreshClassIndex) {
        //                 // 重新签到后还没签
        //                 $item['sign_id'] = 0;
        //             }
        //         }
        //     }
        // }
        // $signCount = 0;
        // $notSignCount = 0;
        // foreach($signData as $item2) {
        //     if($item2['sign_id']) {
        //         $signCount ++;
        //     } else {
        //         $notSignCount ++;
        //     }
        // }

        // 已签到人数
        $signCount = $this->dataModel->get_normal_class_sign_data_count($date, $classId, $refreshClassIndex);
        // 班级人数
        $stuParams['isDelete'] = 0;
        $stuParams['classId'] = $classId;
        $stuParams['getRowNumber'] = true;
        $studentCount = $this->schoolModel->get_student_list($stuParams);
        
        $data['signCount'] = $signCount;
        $data['notSignCount'] = $studentCount - $signCount;
        if($data['notSignCount'] < 0) {
            $data['notSignCount'] = 0; 
        }
        return $data;
    }

    // 获取图片
    private function _get_img_arr($imgs) {
        if(empty($imgs)) {
            return array(
                'imgAll' => array(),
                'imgBeforeEight' => array()
            );
        }
        $imgArr = explode(',', $imgs);   
        $arr['imgAll'] = $imgArr;
        // 如大于8张，取前8张
        $imgBeforeEight = $imgArr;
        $imgAfterEight = array();
        if(count($imgArr) > 8) {
            $imgBeforeEight = array_slice($imgArr, 0, 8);
            $imgAfterEight = array_slice($imgArr, 8);
        }
        $arr['imgBeforeEight'] = $imgBeforeEight;
        $arr['imgAfterEight'] = $imgAfterEight;
        return $arr;
    }

    // 获取图片缩略图
    private function _get_img_arr_thumb($imgs) {
        if(empty($imgs)) {
            return array(
                'imgAll' => array(),
                'imgBeforeEight' => array()
            );
        }
        $imgArr = explode(',', $imgs);
        foreach($imgArr as &$img) {
            $img .= UP_THUMB_IMAGE; 
        }
        $arr['imgAll'] = $imgArr;
        // 如大于8张，取前8张
        $imgBeforeEight = $imgArr;
        $imgAfterEight = array();
        if(count($imgArr) > 8) {
            $imgBeforeEight = array_slice($imgArr, 0, 8);
            $imgAfterEight = array_slice($imgArr, 8);
        }

        // var_export($imgBeforeEight);exit;
        $arr['imgBeforeEight'] = $imgBeforeEight;
        $arr['imgAfterEight'] = $imgAfterEight;
        return $arr;
    }

    // 通过班级数组获取校区数组
    private function _get_campus_by_classes($classIds) {
        $campusIdArr = array();
        $classIdArr = array_unique(explode(',', $classIds));
        foreach($classIdArr as $classId) {
            $class = $this->classesModel->get_class_info($classId);
            if($class) {
                array_push($campusIdArr, $class['campus_id']);
            }
        }
        return implode(',', array_unique($campusIdArr));
    }

    // 通过班级id集合获取班级类型集合，有teaching
    private function _get_classes_types($classIds) {
        $classTypeArr = array();
        $classIdArr = explode(',', $classIds);
        $classIdArr = array_unique($classIdArr);
        foreach($classIdArr as $id) {
            $class = $this->classesModel->get_class_info($id);
            $classType = $class['class_type'];
            if(!in_array($classType, $classTypeArr)) {
                array_push($classTypeArr, $classType);
            }
        }
        return $classTypeArr;
    }

    // 获取考试的科目集合
    private function _get_exam_lessons($classId = 0) {
        if($classId) {
            // 过滤班级
            $classInfo = $this->classesModel->get_class_info($classId);
            // 只获取班牌对应的课室
            $classroomId = $classInfo['classroom_id'];
            $params['locationId'] = $classroomId;
        }
        // 根据日期排序
        $orderBy = 'day ASC, begin ASC';
        $params['orderBy'] = $orderBy;
        // 获取哪些属性
        $params['field'] = 'lesson_id';
        // 考试列表
        $list = $this->dataModel->get_exam_room_detail_list($params);
        // 考试的科目集合
        $lessonArr = array();
        foreach ($list as $key => $val) {
            // 添加科目名
            $lessonInfo = $this->schoolModel->get_lesson_info($val['lesson_id']);
            $list[$key]['lesson_name'] = $lessonInfo['lesson_name'];
            $arr = array(
                'id' => $val['lesson_id'],
                'lesson_name' => $lessonInfo['lesson_name']
            );
            if(!in_array($arr, $lessonArr)) {
                array_push($lessonArr, $arr);
            }
        }
        return $lessonArr;
    }

    /*
     * 通讯录列表页面
    */
    public function phone_book() {
        $this->htmlTitle = '通讯录';
        $params['schoolId'] = $this->user['school_id'];
        $params['campusId'] = $this->user['campus_id'];
        $params['studentId'] = $this->user['id'];
        $params['isDelete'] = 0;
      
        $list = $this->contentModel->get_phone_book_list($params);
        if($list) {
          
        }
        $this->list = $list;
        // var_export($excludePendingList);exit;

        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR . 'phone_book');
    }

    // 通讯录修改页面
    public function phone_book_edit($id = 0) {
        $this->htmlTitle = '通讯录';
        if($id) {
            $addressInfo = $this->contentModel->get_phone_book_info($id);
            if($addressInfo && $addressInfo['is_delete'] == 0) {
                $this->addressInfo = $addressInfo;
            }
        }

        // var_export($this->addressInfo);exit;
        // 获取jssdk参数
        $this->load->library('wechat');
        $url = substr(BASE_URL, 0 , -1) . $_SERVER['REQUEST_URI'];
        $this->dataJssdk = $this->wechat->jssdk_data($url);
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR . 'phone_book_edit');
    }

    // 保存通讯录
    public function save_phone_book_action() {

        $id = $this->post('id');
        $nickname = trim($this->post('nickname'));
        $mobile = trim($this->post('mobile'));
        $headimgurl = $this->post('headimgurl');
        if(empty($nickname)) {
            throw new Exception("昵称不能为空");
        }
        if(empty($mobile)) {
            throw new Exception("号码不能为空");
        }
        // 检验手机号
        // if(!str_is_mobile($mobile)) throw new Exception("请填写正确的手机号码");

        $data['mobile'] = $mobile;
        $data['nickname'] = $nickname;
        $data['headimgurl'] = $headimgurl;
        $data['student_id'] = $this->user['id'];
        $data['school_id'] = $this->user['school_id'];
        $data['campus_id'] = $this->user['campus_id'];
        $data['is_delete'] = 0;
        $data['updatetime'] = date('Y-m-d H:i:s');
        if($id) {
            $data['id'] = $id;
            $msg = '修改成功';
            // var_export($data);exit;
            $this->db->update(ContentModel::$phoneBookTable, $data, "id={$id}");
        } else {
            $data['createtime'] = date('Y-m-d H:i:s');
            $msg = '添加成功';
            $this->db->insert(ContentModel::$phoneBookTable, $data);
        }

        exit(json($msg, true));
    }

    // 删除通讯录
    public function delete_phone_book_action() {
        $id = $this->post('id');
        $data = array(
            'id' => $id,
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->update(ContentModel::$phoneBookTable, $data,  "id={$id}");
        exit(json('删除成功', true));
    }

    // 搜索学生列表
    public function get_student_list() {

        $teacherClassArr = $this->get_classes_by_teacher_id(false, false);
        if($teacherClassArr) {
            $classIdArr = array();
            foreach($teacherClassArr as $class) {
                array_push($classIdArr, $class['id']);
            }
            $classSet = implode(',', $classIdArr);
        } else {
            $classSet = 0;
        }

        // 学生姓名筛选
        if(trim($this->get("keyword"))) $data['keyword'] = trim($this->get("keyword"));
        $data['schoolId'] = $this->user['school_id'];
        $data['classSet'] = $classSet;
        // $data['campusId'] = $this->campusInfo['id'];
        //过滤软删除
        $data['isDelete'] = 0;
        // 按id倒序
        // $data['orderBy'] = '`id` DESC';
        $data['orderBy'] = '`updatetime` DESC';
        $studentList = $this->schoolModel->get_student_list($data);
        // 获取班级列表
        $classParams['schoolId'] = $this->user['school_id'];
        $classParams['isDelete'] = 0;
        $classList = $this->classesModel->get_class_list($classParams);
        $classList = array_value_to_key($classList, 'id');
        // 获取学生其他信息
        foreach($studentList as &$student) {
           $className = '';
           if(isset($classList[$student['class_id']])) {
             $className = $classList[$student['class_id']]['class_name'];
           }
           $student['realnameAndClassname'] = $student['realname'] . '-' . $className;
           // 头像
           if(empty($student['headimgurl'])) {
             $student['headimgurl'] = $this->staticWxUrl . 'assets/img/head.png';
           }
        }
        //  echo'<pre>';var_export($this->teacherClassArr);exit;
        exit(json('', true, $studentList));
    }

    public function teacher_sign_old($teacherIdParam = 0) {
        if($teacherIdParam) {
            $teacherInfo = $this->schoolModel->get_school_user_info($teacherIdParam);
            // $htmlTitle = '教师考勤 -' . $teacherInfo['realname'];
        } else {
            $teacherId = $this->user['id'];
            $teacherInfo = $this->schoolModel->get_school_user_info($teacherId);
            // $htmlTitle = '我的考勤';
        }
        $htmlTitle = '教师考勤 -' . $teacherInfo['realname'];
        if(empty($teacherInfo)) {
            throw new Exception('服务异常');
        }
        // 默认本周日期
        $thisWeekDateArr = get_this_week_date();
        $dateArr['begin_date'] = $thisWeekDateArr[0];
        $dateArr['end_date'] = $thisWeekDateArr[count($thisWeekDateArr) - 1];
        $this->teacherId = $teacherInfo['id'];
        $this->dateArr = $dateArr;

        // 判断是否是学校管理员或年级管理员
        $isSchoolAdmin = false;
        $isGradeAdmin = false;
        // 管理的年级
        $gradeArr = array();
        $schoolAdminCoachList = array();
        $gradeAdminCoachList = array();
        // 没有传teacherid才进入列表页面
        if(empty($teacherIdParam)) {
            if($this->user['user_type'] == USER_TYPE_SCHOOL) {
                $isSchoolAdmin = true;
            } else {
                // 获取学校管理员执教关系
                $this->load->model('staffModel');
                $coachParams['teacherId'] = $teacherInfo['id'];
                $coachParams['coachType'] = COACH_TYPE_SCHOOL_ADMIN;
                $coachParams['schoolId'] = $this->user['school_id'];
                $coachParams['isDelete'] = 0;
                $schoolAdminCoachList = $this->staffModel->get_coach_list($coachParams);
                if($schoolAdminCoachList) {
                    $isSchoolAdmin = true;
                }
                $coachParams['coachType'] = COACH_TYPE_GRADE_ADMIN;
                $gradeAdminCoachList = $this->staffModel->get_coach_list($coachParams);
                if($gradeAdminCoachList) {
                    $isGradeAdmin = true;
                }
            }
        }
        // 学校管理员或年级管理员权限
        if($isGradeAdmin || $isSchoolAdmin) {
            $htmlTitle = '教师考勤列表';
            $this->htmlTitle = $htmlTitle;
            $date = $this->get('date');
            if(empty($date)) {
                // 未设置默认今天
                $date = date('Y-m-d');
            }
            // 获取学校作息
            $scheduleParams['schoolId'] = $teacherInfo['school_id'];
            // 只取本周的
            $scheduleParams['isThisWeek'] = 1;
            $scheduleList = $this->classesModel->get_school_schedule($scheduleParams);
            // 获取第一项即可
            $scheduleInfo = $scheduleList[0];
            $timeArr = json_decode($scheduleInfo['schedule_time_json'], true);        
            $classIndex = $this->dataModel->get_class_index($timeArr, $date);
            // 第几节
            $timeslot = $this->get('timeslot');
            $timeslotArr = array();
            // 当天也显示全部节数
            for($i = 1; $i <= count($timeArr); $i++) {
                $lessonTime = $timeArr[$i - 1];
                $lessonBeginTime = $lessonTime['beginTime'];
                $lessonEndTime = date('H:i', strtotime($lessonTime['beginTime']) + $lessonTime['duration'] * 60);
                $v = '第' . $i . '节 （' . $lessonBeginTime . '-' . $lessonEndTime . '）';
                array_push($timeslotArr, $v);
            }
            if($timeslot) {
                $classIndex = $timeslot;
            }
            // 获取管理的年级
            if($isSchoolAdmin) {
                // 所有年级
                $gradeParams['schoolId'] = $teacherInfo['school_id'];
                $gradeParams['isDelete'] = 0;
                $gradeParams['excludeGraduated'] = 1;
                $gradeParams['excludeFunctional'] = 1;
                $gradeArr = $this->classesModel->get_grade_list($gradeParams);
            } else {
                foreach($gradeAdminCoachList as $gradeAdminCoach) {
                    $gradeInfo = $this->classesModel->get_grade_info($gradeAdminCoach['grade_id']);
                    if($gradeInfo && !in_array($gradeAdminCoach, $gradeArr)) {
                        array_push($gradeArr, $gradeInfo);
                    }
                }
            }
            $this->date = $date;
            $this->classIndex = $classIndex;
            $this->timeslotArr = $timeslotArr;
            $this->gradeArr = $gradeArr;
            // 默认第一个班级
            $this->grade = $gradeArr[0];
                        // echo '<pre>';var_export($gradeArr);exit;
            // 教师考勤列表页面
            $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'teacher_sign_list');
        } else {
            // 普通教师
            // if($teacherId) {
            //     $htmlTitle = '教师考勤 -' . $teacherInfo['realname'];
            // } else {
            //     $htmlTitle = '我的考勤';
            // }
            $htmlTitle = '教师考勤 -' . $teacherInfo['realname'];
            $this->htmlTitle = $htmlTitle;
            // 我的考勤页面
            $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'teacher_sign');
        }
    }

    // 获取教师考勤
    public function get_teacher_sign_old($teacherId = 0) {
        $dateBegin = $this->get('date_begin');
        $dateEnd = $this->get('date_end');
        // 本人登录就获取登录用户id
        $teacherId = $teacherId ? $teacherId : $this->user['id'];
        if($dateBegin > $dateEnd) {
            throw new Exception('开始日期不能大于结束日期');
        }
        // 获取日期数组
        $dateArr = getDateFromRange($dateBegin, $dateEnd);
        if(count($dateArr) > 31) {
            throw new Exception('区间不能超过一个月');
        }
        $teacherInfo = $this->schoolModel->get_teacher_info($teacherId);

        if(empty($teacherInfo)) throw new Exception('服务异常，请联系管理员');

        // 获取某位老师每周的上课天数
        $weekArr = $this->classesModel->get_teacher_schedule_week_arr($teacherInfo);
        // 获取日期区间
        $dateArr = $this->classesModel->get_date_arr_and_filter_week($dateBegin, $dateEnd, $weekArr);
        // 获取学校作息
        $scheduleParams['schoolId'] = $teacherInfo['school_id'];
        // 只取本周的
        $scheduleParams['isThisWeek'] = 1;
        $scheduleList = $this->classesModel->get_school_schedule($scheduleParams);
        // 获取第一项即可
        $schedule = $scheduleList[0];
        // 每天上课节数
        $dailyLessonCount = $schedule['schedule_morning_number'] + $schedule['schedule_afternoon_number'] + $schedule['schedule_early_morning_number'] + $schedule['schedule_night_number']; 
        // 获取教师上课总次数
        $scheduleLessonParams['teacherId'] = $teacherId;
        $scheduleLessonParams['isDelete'] = 0;
        $scheduleLessonParams['leClassIndex'] = $dailyLessonCount;
        $scheduleLessonArr = $this->classesModel->get_school_schedule_lesson($scheduleLessonParams);
        // 周一到周日每天的上课课表
        $scheduleLessonArrByWeek = array();
        foreach($scheduleLessonArr as $scheduleLesson) {
            if(isset($scheduleLessonArrByWeek[$scheduleLesson['schedule_week_index']])) {
                array_push($scheduleLessonArrByWeek[$scheduleLesson['schedule_week_index']], $scheduleLesson);
            } else {
                $scheduleLessonArrByWeek[$scheduleLesson['schedule_week_index']] = array($scheduleLesson);
            }
        }
        // echo '<pre>';var_export($scheduleLessonArrByWeek);exit;
        // 获取考勤数据
        $signParams['schoolId'] = $teacherInfo['school_id'];
        // 开始日期
        $signParams['begindate'] = $dateBegin;
        // 结束日期
        $signParams['enddate'] = $dateEnd;
        // 学生id
        $signParams['studentId'] = $teacherId;
        // 只获取重新签到
        $signParams['isRefreshSign'] = 1;
        $signArr = $this->dataModel->get_teacher_sign_list($signParams);
        $dateSignArr = array();
        // 获取上课总次数
        $scheduleLessonCount = 0;
        foreach($dateArr as $date) {
            $signCount = $lateCount = 0;
            foreach($signArr as $sign) {
                if($sign['sign_date'] == $date) {
                    if($sign['is_supplement']) {
                        // 补签
                        $lateCount++;
                    } else {
                        // 正常签到
                        $signCount++;
                    }
                }
            }
            
            // 转换日期格式，2021年6月11日  星期二
            $tempArr = explode('-', $date);
            $dateFormat = $tempArr[0] . '年' . $tempArr[1] . '月' . $tempArr[2] . '日';
            $dateSignArr[$date] = array(
                'sign' => $signCount,
                'late' => $lateCount,
                'week' => date_to_week_format_new($date),
                'date' => $date,
                'dateFormat' => $dateFormat
            );

            // 计算上课总次数
            $w = date('w', strtotime($date));
            if($w == 0) {
                // 周日为7
                $w = 7;
            }
            if(isset($scheduleLessonArrByWeek[$w])) {
                $scheduleLessonCount += count($scheduleLessonArrByWeek[$w]);
            }
        }
        // 计算缺勤总次数
        $absenceCount = $scheduleLessonCount - count($signArr);
        $absenceCount = $absenceCount > 0 ? $absenceCount : 0;
        // $signArr = array_reverse($signArr);
        // echo '<pre>';var_export($absenceCount);exit;
        $res = array(
            'absenceCount' => $absenceCount,
            'dateSignArr' => $dateSignArr
        );
        exit(json('', true, $res));
    }

    /*
     * 签到详情页面v2
    */
    public function teacher_sign_detail_old($teacherId) {
        $this->htmlTitle = '教师考勤详情';
        $signdate = $this->get('date') ? $this->get('date') : date('Y-m-d');
        // 获取学生信息
        $teacherInfo = $this->schoolModel->get_teacher_info($teacherId);
        // 获取考勤数据
        $signParams['schoolId'] = $teacherInfo['school_id'];
        // 签到日期
        $signParams['signdate'] = $signdate;
        // 学生id
        $signParams['studentId'] = $teacherId;
        // 只获取重新签到
        $signParams['isRefreshSign'] = 1;
        $signArr = $this->dataModel->get_teacher_sign_list($signParams);
        // 颠倒顺序
        $signArr = array_reverse($signArr);
        // echo '<pre>';var_export($signArr);exit;
        // 获取本校全部班级
        $classParams['schoolId'] = $teacherInfo['school_id'];
        $classList = $this->classesModel->get_class_list($classParams);
        $classList = array_value_to_key($classList, 'id');
        foreach($signArr as &$sign) {
            // 获取班级名称
            if(isset($classList[$sign['class_id']])) {
                $sign['className'] = $classList[$sign['class_id']]['class_name'];
            } else {
                $sign['className'] = '';
            }
            // 截取签到时间，分：秒
            $signTime = explode(' ', $sign['createtime'])[1];
            $signH = explode(':', $signTime)[0];
            $signM = explode(':', $signTime)[1];
            $sign['signTimeFormat'] = $signH . ':' . $signM;
        }

        // echo '<pre>';var_export($classList);exit;

        $this->signdate = $signdate;
        $this->week = date_to_week_format_new($signdate);
        $this->teacherInfo = $teacherInfo;
        $this->signArr = $signArr;

        // 获取jssdk参数
        $this->load->library('wechat');
        $url = substr(BASE_URL, 0 , -1) . $_SERVER['REQUEST_URI'];
        $this->dataJssdk = $this->wechat->jssdk_data($url);
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'teacher_sign_detail');
    }

    // 获取年级某天的教师考勤数据
    function get_grade_date_teacher_sign_data_old() {
        $this->load->model('staffModel');
        $gradeId = $this->get('grade_id');
        $date = $this->get('date');
        // 第几节
        $timeslot = $this->get('timeslot');
        if(empty($date)) {
            // 未设置默认今天
            $date = date('Y-m-d');
        }
        $gradeInfo = $this->classesModel->get_grade_info($gradeId);

        // 获取学校作息
        $scheduleParams['schoolId'] = $this->user['school_id'];
        // 只取本周的
        $scheduleParams['isThisWeek'] = 1;
        $scheduleList = $this->classesModel->get_school_schedule($scheduleParams);
        // 获取第一项即可
        $scheduleInfo = $scheduleList[0];
        $timeArr = json_decode($scheduleInfo['schedule_time_json'], true);
        $classIndex = $this->dataModel->get_class_index($timeArr, $date);
        $timeslotArr = array();
        for($i = 1; $i <= $classIndex; $i++) {
            $lessonTime = $timeArr[$i - 1];
            $lessonBeginTime = $lessonTime['beginTime'];
            $lessonEndTime = date('H:i', strtotime($lessonTime['beginTime']) + $lessonTime['duration'] * 60); 

            $v = '第' . $i . '节 （' . $lessonBeginTime . '-' . $lessonEndTime . '）';
            array_push($timeslotArr, $v);
        }
        if($timeslot) {
            $classIndex = $timeslot;
        }

       // 获取教师考勤数据
       $signParams['schoolId'] = $this->user['school_id'];
       $signParams['signDate'] = $date;
       $signParams['scheduleClassIndex'] = $classIndex;
       $signParams['isRefreshSign'] = 1;
       $signDataArr = $this->dataModel->get_teacher_sign_data($signParams);
       // 使用teacher_id作为键值
       $signDataArr = array_value_to_key($signDataArr, 'student_id');
       // 获取学校本节课的课程
       $scheduleLessonParams['schoolId'] = $this->user['school_id'];
       $scheduleLessonParams['scheduleId'] = $scheduleInfo['id'];
       $scheduleLessonParams['weekIndex'] = date('w', strtotime($date)) == 0 ? 7 : date('w', strtotime($date)); // 周日为7，不为0
       $scheduleLessonParams['classIndex'] = $classIndex;
       $scheduleLessonArr = $this->classesModel->get_school_schedule_lesson($scheduleLessonParams);
       // 获取全校老师
       $teacherParams['schoolId'] = $this->user['school_id'];
       $teacherParams['isDelete'] = 0;
       $schoolTeacherList = $this->schoolModel->get_teacher_list($teacherParams);
       // 使用id作为键值
       $schoolTeacherList = array_value_to_key($schoolTeacherList, 'id');
       // 获取年级班级列表
       $classParams['schoolId'] = $this->user['school_id'];
       $classParams['gradeId'] = $gradeInfo['id'];
       $classParams['isDelete'] = 0;
       $gradeClassList = $this->classesModel->get_class_list($classParams);
       $gradeClassIdArr = array();
       foreach($gradeClassList as $gradeClass) {
           array_push($gradeClassIdArr, $gradeClass['id']);
       }
       // 班级id集合
       $gradeClassIdSet = implode(',', $gradeClassIdArr);
       // 获取执教关系
       $coachParams['schoolId'] = $this->user['school_id'];
       $coachParams['coachType'] = COACH_TYPE_TEACHER;
       $coachParams['classSet'] = $gradeClassIdSet;
       $coachList = $this->staffModel->get_coach_list($coachParams);
       // 使用teacher_id作为键值
       $coachList = array_value_to_key($coachList, 'teacher_id');
       // 获取该节课需要上课的老师列表
       $scheduleTeacherList = array();
       foreach($scheduleLessonArr as $scheduleLesson) {
           // 任课老师不为空
           if($scheduleLesson['schedule_teacher']) {
                // 支持多个授课老师
                $scheduleTeacherIdArr = explode(',', $scheduleLesson['schedule_teacher']);
                foreach($scheduleTeacherIdArr as $scheduleTeacherId) {
                    // 是否执教该年级
                    if(isset($schoolTeacherList[$scheduleTeacherId]) && isset($coachList[$scheduleTeacherId])){
                        $scheduleTeacherList[$scheduleTeacherId] = $schoolTeacherList[$scheduleTeacherId];
                    }
                }
           }
       }

        $signData = array();
        $notSignData = array();
        foreach($scheduleTeacherList as $teacherId => $scheduleTeacher) {
            if(isset($signDataArr[$teacherId])) {
                if($signDataArr[$teacherId]['is_supplement']) {
                    $scheduleTeacher['signState'] = '<span class="text-danger">迟到补签</span>';
                } else {
                    $scheduleTeacher['signState'] = '<span class="text-success">正常签到</span>';
                }
                // 签到时间，去除日期
                $scheduleTeacher['signTimeExcludeDate'] = explode(' ', $signDataArr[$teacherId]['createtime'])[1];
                array_push($signData, $scheduleTeacher);
            } else {
                array_push($notSignData, $scheduleTeacher);
            }
        }

        if($signData) {
            // 按签到时间排序
            $timeKey =  array_column($signData, 'signTimeExcludeDate');
            array_multisort($timeKey, SORT_DESC, $signData);
        }
        $res = array(
            'sign_data' => $signData,
            'not_sign_data' => $notSignData
        );
        // echo'<pre>';var_export($signData);exit;
        exit(json('', true, $res));
    }

    public function teacher_sign($teacherIdParam = 0) {
        if($teacherIdParam) {
            $teacherInfo = $this->schoolModel->get_school_user_info($teacherIdParam);
            // $htmlTitle = '教师考勤 -' . $teacherInfo['realname'];
        } else {
            $teacherId = $this->user['id'];
            $teacherInfo = $this->schoolModel->get_school_user_info($teacherId);
            // $htmlTitle = '我的考勤';
        }
        $htmlTitle = '教师考勤 -' . $teacherInfo['realname'];
        if(empty($teacherInfo)) {
            throw new Exception('服务异常');
        }
        // 默认本周日期
        $thisWeekDateArr = get_this_week_date();
        $dateArr['begin_date'] = $thisWeekDateArr[0];
        $dateArr['end_date'] = $thisWeekDateArr[count($thisWeekDateArr) - 1];
        $this->teacherId = $teacherInfo['id'];
        $this->dateArr = $dateArr;

        // 判断是否是学校管理员或年级管理员
        $isSchoolAdmin = false;
        $isGradeAdmin = false;
        // 管理的年级
        $gradeArr = array();
        $schoolAdminCoachList = array();
        $gradeAdminCoachList = array();
        // 没有传teacherid才进入列表页面
        if(empty($teacherIdParam)) {
            if($this->user['user_type'] == USER_TYPE_SCHOOL) {
                $isSchoolAdmin = true;
            } else {
                // 获取学校管理员执教关系
                $this->load->model('staffModel');
                $coachParams['teacherId'] = $teacherInfo['id'];
                $coachParams['coachType'] = COACH_TYPE_SCHOOL_ADMIN;
                $coachParams['schoolId'] = $this->user['school_id'];
                $coachParams['isDelete'] = 0;
                $schoolAdminCoachList = $this->staffModel->get_coach_list($coachParams);
                if($schoolAdminCoachList) {
                    $isSchoolAdmin = true;
                }
                $coachParams['coachType'] = COACH_TYPE_GRADE_ADMIN;
                $gradeAdminCoachList = $this->staffModel->get_coach_list($coachParams);
                if($gradeAdminCoachList) {
                    $isGradeAdmin = true;
                }
            }
        }
        // 学校管理员或年级管理员权限
        if($isGradeAdmin || $isSchoolAdmin) {
            $htmlTitle = '教师考勤缺勤记录';
            $this->htmlTitle = $htmlTitle;
            $date = $this->get('date');
            if(empty($date)) {
                // 未设置默认今天
                $date = date('Y-m-d');
            }
            // 获取学校作息
            $scheduleParams['schoolId'] = $teacherInfo['school_id'];
            // 只取本周的
            $scheduleParams['isThisWeek'] = 1;
            $scheduleList = $this->classesModel->get_school_schedule($scheduleParams);
            // 获取第一项即可
            $scheduleInfo = $scheduleList[0];
            // 支持早读，晚间
            $timeslotPrefixArr = array();
            if($scheduleInfo['schedule_early_morning_number'] > 0) {
                for($i = 0;$i < $scheduleInfo['schedule_early_morning_number'];$i++) {
                    $tmpIndex = $i + 1;
                    $timeslotPrefixArr[] = '早间' . $tmpIndex;
                }
            }
            $dayScheduleNum = $scheduleInfo['schedule_morning_number'] + $scheduleInfo['schedule_afternoon_number'];
            for($i = 0;$i < $dayScheduleNum;$i++) {
                $tmpIndex = $i + 1;
                $timeslotPrefixArr[] = '第' . $tmpIndex . '节';
            }
            if($scheduleInfo['schedule_night_number'] > 0) {
                for($i = 0;$i < $scheduleInfo['schedule_night_number'];$i++) {
                    $tmpIndex = $i + 1;
                    $timeslotPrefixArr[] = '晚间' . $tmpIndex;
                }
            }

            $timeArr = json_decode($scheduleInfo['schedule_time_json'], true);        
            // $classIndex = $this->dataModel->get_class_index($timeArr, $date);
            $timeslotArr = array();
            // 当天也显示全部节数
            for($i = 1; $i <= count($timeArr); $i++) {
                $lessonTime = $timeArr[$i - 1];
                $lessonBeginTime = $lessonTime['beginTime'];
                $lessonEndTime = date('H:i', strtotime($lessonTime['beginTime']) + $lessonTime['duration'] * 60);
                if(isset($timeslotPrefixArr[$i - 1])) {
                    $prefix = $timeslotPrefixArr[$i - 1];
                } else {
                    $prefix = '';
                }
                $v = $prefix . '（' . $lessonBeginTime . '-' . $lessonEndTime . '）';
                array_push($timeslotArr, $v);
            }
            // if($timeslot) {
            //     $classIndex = $timeslot;
            // }
            // 获取管理的年级
            if($isSchoolAdmin) {
                // 所有年级
                $gradeParams['schoolId'] = $teacherInfo['school_id'];
                $gradeParams['isDelete'] = 0;
                $gradeParams['excludeGraduated'] = 1;
                $gradeParams['excludeFunctional'] = 1;
                $gradeArr = $this->classesModel->get_grade_list($gradeParams);
            } else {
                foreach($gradeAdminCoachList as $gradeAdminCoach) {
                    $gradeInfo = $this->classesModel->get_grade_info($gradeAdminCoach['grade_id']);
                    if($gradeInfo && !in_array($gradeAdminCoach, $gradeArr)) {
                        array_push($gradeArr, $gradeInfo);
                    }
                }
            }
            // 第几节
            $timeslot = $this->get('timeslot') ? $this->get('timeslot') : 0;
            // 默认获取所有节数
            $this->classIndex = $timeslot;
            if($timeslot == 0) {
                $this->classIndexStr = '全部';
            } else {
                $this->classIndexStr = '第' . $timeslot . '节';
            }
            $this->date = $date;
            $this->timeslotArr = $timeslotArr;
            $this->gradeArr = $gradeArr;
            // 默认第一个班级
            $this->grade = $gradeArr[0];
            $this->timeslotPrefixArr = $timeslotPrefixArr;
            // echo '<pre>';var_export($gradeArr);exit;
            // 教师考勤列表页面
            $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'teacher_sign_list');
        } else {
            // 普通教师
            // if($teacherId) {
            //     $htmlTitle = '教师考勤 -' . $teacherInfo['realname'];
            // } else {
            //     $htmlTitle = '我的考勤';
            // }
            $htmlTitle = '教师考勤 -' . $teacherInfo['realname'];
            $this->htmlTitle = $htmlTitle;
            // 我的考勤页面
            $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'teacher_sign');
        }
    }
    // 获取年级某天的教师考勤数据
    function get_grade_date_teacher_sign_data() {
        $this->load->model('staffModel');
        $gradeId = $this->get('grade_id');
        $date = $this->get('date');
        // 第几节
        $timeslot = $this->get('timeslot');
        if(empty($date)) {
            // 未设置默认今天
            $date = date('Y-m-d');
        }
        // $gradeInfo = $this->classesModel->get_grade_info($gradeId);
        // 签到时间区间
        $data['schoolId'] = $this->user['school_id'];
        $data['gradeId'] = $gradeId;
        $data['signDate'] = $date;
        // 节数，0即是选择全部节数
        if($timeslot != 0) {
            $data['scheduleClassIndexSet'] = $timeslot;
        }
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        // echo'<pre>';var_export($timeslot);exit;
        // 按id倒序
        $signList = $this->dataModel->get_teacher_sign_record_list($data);
        // 获取班级列表
        $classParams['schoolId'] = $this->user['school_id'];
        //过滤软删除
        $classParams['isDelete'] = 0;
        $classList = $this->classesModel->get_class_list($classParams);
        // 使用id作为键值
        $classList = array_value_to_key($classList, 'id');
        // 获取教师列表
        $teacherParams['schoolId'] = $this->user['school_id'];
        $teacherParams['allUserType'] = 1;
        //过滤软删除
        $teacherParams['isDelete'] = 0;
        $teacherList = $this->schoolModel->get_teacher_list($teacherParams);
        // 使用id作为键值
        $teacherList = array_value_to_key($teacherList, 'id');
        foreach($signList as &$sign) {
            // 星期几 
            $sign['schedule_week_index'] = date_to_week_format_new($sign['sign_date']);
            
            // 任课班级
            if(isset($classList[$sign['course_class_id']])) {
                $sign['courseClassName'] = $classList[$sign['course_class_id']]['class_name'];
            } else {
                $sign['courseClassName'] = '';
            }
            // 获取教师人脸
            if(isset($teacherList[$sign['teacher_id']])) {
                $sign['face_image'] = $teacherList[$sign['teacher_id']]['face_image'];
            } else {
                $sign['face_image'] = '';
            }
            // 考勤状态
            if($sign['has_sign']) {
                if($sign['is_supplement']) {
                    $sign['signState'] = '<span class="label label-primary">迟到补签</span>';
                } else {
                    $sign['signState'] = '<span class="label label-success">正常考勤</span>';
                }
            } else {
                $sign['signState'] = '<span class="label label-danger">缺&nbsp;&nbsp;&nbsp;&nbsp;勤</span>';
            }
            // 转换签到时间格式，09:00
            if($sign['has_sign']) {
                $timeStrTemp = explode(' ', $sign['signtime'])[1];
                $timeArrTemp = explode(':', $timeStrTemp);
                $sign['signTimeFormat'] = $timeArrTemp[0] . ':' . $timeArrTemp[1];
            }
        }

        // echo'<pre>';var_export($signData);exit;
        exit(json('', true, $signList));
    }
    // 保存教师缺勤记录
    public function save_teacher_sign_record_remark_action() {
        $id = $this->post("id");
        $content = $this->post("content") ? $this->post("content") : '';
        $save = array(
            'remark' => $content,
            'remark_user_id' => $this->user['id'],
            'remarktime' => date('Y-m-d H:i:s')
        );
        $this->db->update(DataModel::$teacherSignRecordTable, $save,"id='{$id}'");

        exit(json("修改备注成功", true));
    }
    // 获取教师考勤
    public function get_teacher_sign($teacherId = 0) {
        $dateBegin = $this->get('date_begin');
        $dateEnd = $this->get('date_end');
        // 本人登录就获取登录用户id
        $teacherId = $teacherId ? $teacherId : $this->user['id'];
        if($dateBegin > $dateEnd) {
            throw new Exception('开始日期不能大于结束日期');
        }
        // 获取日期数组
        $dateArr = getDateFromRange($dateBegin, $dateEnd);
        if(count($dateArr) > 31) {
            throw new Exception('区间不能超过一个月');
        }
        $teacherInfo = $this->schoolModel->get_teacher_info($teacherId);
        if(empty($teacherInfo)) throw new Exception('服务异常，请联系管理员');
        // 获取某位老师每周的上课天数
        $weekArr = $this->classesModel->get_teacher_schedule_week_arr($teacherInfo);
        // 获取日期区间
        $dateArr = $this->classesModel->get_date_arr_and_filter_week($dateBegin, $dateEnd, $weekArr);
         // 签到时间区间
         $data['schoolId'] = $this->user['school_id'];
         // 开始日期
         $data['begindate'] = $dateBegin;
         // 结束日期
         $data['enddate'] = $dateEnd;
         // 学生id
         $data['teacherId'] = $teacherId;

        // 按id倒序
        $signList = $this->dataModel->get_teacher_sign_record_list($data);
       
        // echo'<pre>';var_export($signList);exit;

        $dateSignArr = array();
        $signAllCount = $lateAllCount = $absenceAllCount = 0;
        foreach($dateArr as $date) {
            $signCount = $lateCount = $absenceCount = 0;
            foreach($signList as $sign) {
                if($sign['sign_date'] == $date) {
                    if($sign['has_sign']) {
                        if($sign['is_supplement']) {
                            // 补签
                            $lateCount++;
                            $lateAllCount++;
                        } else {
                            // 正常签到
                            $signCount++;
                            $signAllCount++;
                        }
                    } else {
                        // 缺勤
                        $absenceCount++;
                        $absenceAllCount++;
                    }
                }
            }
            
            // 转换日期格式，2021年6月11日  星期二
            $tempArr = explode('-', $date);
            $dateFormat = $tempArr[0] . '年' . $tempArr[1] . '月' . $tempArr[2] . '日';
            $dateSignArr[$date] = array(
                'sign' => $signCount,
                'late' => $lateCount,
                'absence' => $absenceCount,
                'week' => date_to_week_format_new($date),
                'date' => $date,
                'dateFormat' => $dateFormat
            );

            // // 计算上课总次数
            // $w = date('w', strtotime($date));
            // if($w == 0) {
            //     // 周日为7
            //     $w = 7;
            // }
            // if(isset($scheduleLessonArrByWeek[$w])) {
            //     $scheduleLessonCount += count($scheduleLessonArrByWeek[$w]);
            // }
        }
            // echo '<pre>';var_export($dateSignArr);exit;
        // $signArr = array_reverse($signArr);

        $res = array(
            'allCount' => array(
                'sign' => $signAllCount,
                'late' => $lateAllCount,
                'absence' => $absenceAllCount
            ),
            'dateSignArr' => $dateSignArr
        );
        exit(json('', true, $res));
    }
    /*
     * 签到详情页面v2
    */
    public function teacher_sign_detail($teacherId) {
        $this->htmlTitle = '教师考勤详情';
        $signdate = $this->get('date') ? $this->get('date') : date('Y-m-d');
        // 获取学生信息
        $teacherInfo = $this->schoolModel->get_teacher_info($teacherId);
        // 签到时间区间
        $data['schoolId'] = $this->user['school_id'];
        $data['signDate'] = $signdate;
        // 学生id
        $data['teacherId'] = $teacherId;

        // 按id倒序
        $signArr = $this->dataModel->get_teacher_sign_record_list($data);
        // 颠倒顺序
        $signArr = array_reverse($signArr);
        // echo '<pre>';var_export($signArr);exit;
        // 获取本校全部班级
        $classParams['schoolId'] = $teacherInfo['school_id'];
        $classList = $this->classesModel->get_class_list($classParams);
        $classList = array_value_to_key($classList, 'id');
        // 获取本校全部课室
        $roomParams['schoolId'] = $teacherInfo['school_id'];
        $roomParams['isDelete'] = 0;
        $roomList = $this->classesModel->get_classroom_list($roomParams);
        // 使用id作为键值
        $roomList = array_value_to_key($roomList, 'id');
        // 获取学校作息
        $scheduleParams['schoolId'] = $this->user['school_id'];
        // 只取本周的
        $scheduleParams['isThisWeek'] = 1;
        $scheduleList = $this->classesModel->get_school_schedule($scheduleParams);
        // 获取第一项即可
        $scheduleInfo = $scheduleList[0];
        $timeArr = json_decode($scheduleInfo['schedule_time_json'], true);
        // 当前第几节
        $classIndex = $this->dataModel->get_class_index($timeArr, $signdate);
        foreach($signArr as &$sign) {
            // 获取任课班级名称
            if(isset($classList[$sign['course_class_id']])) {
                $sign['courseClassName'] = $classList[$sign['course_class_id']]['class_name'];
            } else {
                $sign['courseClassName'] = '';
            }
             // 上课地点
             if(isset($roomList[$sign['schedule_room_id']])) {
                $sign['scheduleRoomName'] = $roomList[$sign['schedule_room_id']]['classroom_name'];
            } else {
                $sign['scheduleRoomName'] = '';
            }
            // 星期几 
            $sign['schedule_week_index'] = date_to_week_format_new($sign['sign_date']);       
            // 获取教师人脸
            if(isset($teacherList[$sign['teacher_id']])) {
                $sign['face_image'] = $teacherList[$sign['teacher_id']]['face_image'];
            } else {
                $sign['face_image'] = '';
            }
            // 考勤状态
            if($sign['has_sign']) {
                if($sign['is_supplement']) {
                    $sign['signState'] = '<span class="label label-primary">迟到补签</span>';
                } else {
                    $sign['signState'] = '<span class="label label-success">正常考勤</span>';
                }
            } else {
                // 判断是否到了考勤时间
                if($sign['sign_date'] == date('Y-m-d') && $sign['schedule_class_index'] > $classIndex) {
                    $sign['signState'] = '<span class="label label-warning">未到考勤时间</span>';
                } else {
                    $sign['signState'] = '<span class="label label-danger">缺&nbsp;&nbsp;&nbsp;&nbsp;勤</span>';
                }
                
            }
            // 转换签到时间格式，09:00
            if($sign['has_sign']) {
                $timeStrTemp = explode(' ', $sign['signtime'])[1];
                $timeArrTemp = explode(':', $timeStrTemp);
                $sign['signTimeFormat'] = $timeArrTemp[0] . ':' . $timeArrTemp[1];
            }
        }

        // echo '<pre>';var_export($signArr);exit;

        $this->signdate = $signdate;
        $this->week = date_to_week_format_new($signdate);
        $this->teacherInfo = $teacherInfo;
        $this->signArr = $signArr;

        // 获取jssdk参数
        $this->load->library('wechat');
        $url = substr(BASE_URL, 0 , -1) . $_SERVER['REQUEST_URI'];
        $this->dataJssdk = $this->wechat->jssdk_data($url);
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'teacher_sign_detail');
    }

    /*
     * 班级通知已读页面
    */
    public function notify_user_read($notifyId) {
        $this->htmlTitle = '班级通知已读情况';

        // 获取通知详情
        $notifyInfo = $this->contentModel->get_notify_info($notifyId);
        // 发布班级
        $classParams['schoolId'] = $notifyInfo['school_id'];
        $classParams['classId'] = $notifyInfo['class_id'];
        $classParams['isDelete'] = 0;
        $classArr = $this->classesModel->get_class_list($classParams);
        // echo '<pre>';var_export($this->teacherClassArr);exit;
        // 获取该通知的已读列表
        $readParams['schoolId'] = $notifyInfo['school_id'];
        $readParams['bindUserType'] = BIND_TYPE_STUDENT;
        $readParams['itemId'] = $notifyId;
        $readParams['itemType'] = READ_TYPE_NOTIFY;
        $userReadList = $this->wxUserModel->get_wx_user_read_list($readParams);
        // 使用userId作为键值
        $userReadList = array_value_to_key($userReadList, 'user_id');
        if($classArr) {
            foreach($classArr as $key => $class) {
                // 获取某班级所有学生
                $stuParams['schoolId'] = $this->user['school_id'];
                // 包含教学班
                $stuParams['classORteach'] = $class['id'];
                $stuParams['isDelete'] = 0;
                $studentArr = $this->schoolModel->get_student_list($stuParams);
                if($studentArr) {
                    foreach($studentArr as $k => $student) {
                        // 判断是否已读
                        if(isset($userReadList[$student['id']])) {
                            $studentArr[$k]['hasReadSort'] = 1;
                            $studentArr[$k]['hasRead'] = '<span class="text-success">已读</span>';
                        } else {
                            $studentArr[$k]['hasReadSort'] = 0;
                            $studentArr[$k]['hasRead'] = '<span class="text-danger">未读</span>';
                        }
                    }
                    // 已读排前面
                    $timeKey =  array_column($studentArr, 'hasReadSort');
                    array_multisort($timeKey, SORT_DESC, $studentArr);
                }

                $classArr[$key]['studentArr'] = $studentArr;
            }
        }
        $this->notifyInfo = $notifyInfo;
        $this->classArr = $classArr;
        // echo '<pre>';var_export($userReadList);exit;

        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'user_read' . DIRECTORY_SEPARATOR . 'notify_user_read');
    }

    /*
     * 校园公告已读页面
    */
    public function announce_user_read($announceId) {
        $this->htmlTitle = '校园通知已读情况';

        // 获取公告详情
        $announceInfo = $this->contentModel->get_announce_info($announceId);
        // 发布班级
        $classParams['schoolId'] = $announceInfo['school_id'];
        $classParams['classType'] = CLASSES_TYPE_NORMAL;
        $classParams['isDelete'] = 0;
        $classArr = $this->classesModel->get_class_list($classParams);
        // echo '<pre>';var_export($this->teacherClassArr);exit;
        // 获取该通知的已读列表
        $readParams['schoolId'] = $announceInfo['school_id'];
        $readParams['bindUserType'] = BIND_TYPE_STUDENT;
        $readParams['itemId'] = $announceId;
        $readParams['itemType'] = READ_TYPE_ANNOUNCE;
        $userReadList = $this->wxUserModel->get_wx_user_read_list($readParams);
        // 使用userId作为键值
        $userReadList = array_value_to_key($userReadList, 'user_id');
        if($classArr) {
            foreach($classArr as $key => $class) {
                // 获取某班级所有学生
                $stuParams['schoolId'] = $this->user['school_id'];
                // 包含教学班
                $stuParams['classORteach'] = $class['id'];
                $stuParams['isDelete'] = 0;
                $studentArr = $this->schoolModel->get_student_list($stuParams);
                if($studentArr) {
                    foreach($studentArr as $k => $student) {
                        // 判断是否已读
                        if(isset($userReadList[$student['id']])) {
                            $studentArr[$k]['hasReadSort'] = 1;
                            $studentArr[$k]['hasRead'] = '<span class="text-success">已读</span>';
                        } else {
                            $studentArr[$k]['hasReadSort'] = 0;
                            $studentArr[$k]['hasRead'] = '<span class="text-danger">未读</span>';
                        }
                    }
                    // 已读排前面
                    $timeKey =  array_column($studentArr, 'hasReadSort');
                    array_multisort($timeKey, SORT_DESC, $studentArr);
                }

                $classArr[$key]['studentArr'] = $studentArr;
            }
        }
        $this->announceInfo = $announceInfo;
        $this->classArr = $classArr;
        // echo '<pre>';var_export($userReadList);exit;

        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'user_read' . DIRECTORY_SEPARATOR . 'announce_user_read');
    }

    // 已读列表，搜索学生列表
    public function get_student_list_for_user_read() {
        $classSet = $this->get('class_set') ?  $this->get('class_set') : 0; // 班级id集合
        $readItemType = $this->get('read_type') ?  $this->get('read_type') : 0; // 已读对象类型
        $readItemId = $this->get('item_id') ?  $this->get('item_id') : 0;       // 已读对象id
        // 学生姓名筛选
        if(trim($this->get("keyword"))) $data['keyword'] = trim($this->get("keyword"));
        $data['schoolId'] = $this->user['school_id'];
        if($classSet) {
            // 没传就是获取全校学生
            $data['classSet'] = $classSet;
        }
        //过滤软删除
        $data['isDelete'] = 0;
        $data['orderBy'] = '`updatetime` DESC';
        $studentList = $this->schoolModel->get_student_list($data);
        // 获取班级列表
        $classParams['schoolId'] = $this->user['school_id'];
        $classParams['isDelete'] = 0;
        $classList = $this->classesModel->get_class_list($classParams);
        $classList = array_value_to_key($classList, 'id');
        // 获取已读列表
        $readParams['schoolId'] = $this->user['school_id'];
        $readParams['bindUserType'] = BIND_TYPE_STUDENT;
        $readParams['itemId'] = $readItemId;
        $readParams['itemType'] = $readItemType;
        $userReadList = $this->wxUserModel->get_wx_user_read_list($readParams);
        // 使用userId作为键值
        $userReadList = array_value_to_key($userReadList, 'user_id');
        // 获取学生其他信息
        foreach($studentList as &$student) {
            $className = '';
            if(isset($classList[$student['class_id']])) {
                $className = $classList[$student['class_id']]['class_name'];
            }
            $student['realnameAndClassname'] = $student['realname'] . '——' . $className;
            // 头像
            if(empty($student['headimgurl'])) {
                $student['headimgurl'] = $this->staticWxUrl . 'assets/img/head.png';
            }
            // 判断是否已读
            if(isset($userReadList[$student['id']])) {
                $student['hasReadSort'] = 1;
                $student['hasRead'] = '<span class="text-success">已读</span>';
            } else {
                $student['hasReadSort'] = 0;
                $student['hasRead'] = '<span class="text-danger">未读</span>';
            }
        }
         // 已读排前面
         $timeKey =  array_column($studentList, 'hasReadSort');
         array_multisort($timeKey, SORT_DESC, $studentList);
        //  echo'<pre>';var_export($this->teacherClassArr);exit;
        exit(json('', true, $studentList));
    }

    /*
     * 闸机记录页面
    */
    public function gate_sign() {
        $this->htmlTitle = '闸机记录';
        $date = date('Y-m-d');
        $classId = '';
        $keyword = '';
        // 获取筛选参数session
        $sessArr = $this->session->userdata('gate_sign');
        if($sessArr) {
            if(isset($sessArr['date']) && $sessArr['date']) {
                $date = $sessArr['date'];
            }
            if(isset($sessArr['class_id']) && $sessArr['class_id']) {
                $classId = $sessArr['class_id'];
            }
            if(isset($sessArr['keyword']) && $sessArr['keyword']) {
                $keyword = $sessArr['keyword'];
            }
        }
        $this->date = $date;

        // echo'<pre>';var_export($this->classId);exit;
        if($this->bindUserType == BIND_TYPE_TEACHER) {
            // 判断是否学校管理员
            // 获取学校管理员对应的年级列表
            $isSchoolAdmin = false;
            if($this->user['user_type'] == USER_TYPE_SCHOOL) {
                $isSchoolAdmin = true;
            } else {
                $this->load->model('staffModel');
                $coachParams['teacherId'] = $this->user['id'];
                $coachParams['coachType'] = COACH_TYPE_SCHOOL_ADMIN; 
                $schoolAdminCoachList = $this->staffModel->get_coach_list($coachParams);
                if($schoolAdminCoachList) {
                    $isSchoolAdmin = true;
                }
            }
            // 管理员可以查看走班
            if($isSchoolAdmin) {
                // echo'<pre>';var_export($this->user);exit;
                 // 管理员权限
                $this->teacherClassArr = $this->get_classes_by_teacher_id(false, true);
            } else {
                // 教师权限（可以查看走班）
                $this->teacherClassArr = $this->get_classes_by_teacher_id(false, true);
            }
            if(empty($classId) && !empty($this->teacherClassArr)) {
                // 如未筛选某个班级，默认选择第一个班级
                $class = $this->teacherClassArr['0'];
            } else {
                $class = $this->classesModel->get_class_info($classId);
            }
            $this->class = $class;
            $this->classId = $classId;
            $this->keyword = $keyword;
        }
        
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'classes/sign/gate_sign');
    }
    // 获取班级某天的闸机考勤数据
    function get_class_date_gate_sign_data() {
        $classId = $this->get('class_id');
        $date = $this->get('date');
        if(empty($date)) {
            // 未设置默认今天
            $date = date('Y-m-d');
        }
        
        if($classId) {
            // 获取学生列表
            $stuParams['isDelete'] = 0;
            $stuParams['schoolId'] = $this->user['school_id'];
            $stuParams['classId'] = $classId;
            $studentList = $this->schoolModel->get_student_list($stuParams);
        }
        if($this->get('student_id')) {
            $studentList = array();
            $studentList[] = $this->schoolModel->get_student_info($this->get('student_id'));
             
        }
        // 使用id作为键值
        $studentList = array_value_to_key($studentList, 'id');
       
        // 获取闸机列表
        $gateParams['schoolId'] = $this->user['school_id'];
        $gateParams['isDelete'] = 0;
        $gateList = $this->schoolModel->get_gate_list($gateParams);
        // 使用device_sn作为键值
        $gateList = array_value_to_key($gateList, 'device_sn');

        $signParams['type'] = SIGN_TYPE_GATE;
        $signParams['signdate'] = $date;
        if($classId) {
            $signParams['classId'] = $classId;
        }
        if($this->get('keyword')) {
            $signParams['keyword'] = $this->get('keyword');
        }
        if($this->get('student_id')) {
            $signParams['studentId'] = $this->get('student_id');
        }
        // 时段，早中晚
        if($this->get('time')) {
            $time = $this->get('time');
            $beginTime = '';
            $endTime = '';
            if($time == 1) {
                // 早
                $beginTime = '00:00:00';
                $endTime = '11:59:59';
            } elseif($time == 2) {
                // 中
                $beginTime = '12:00:00';
                $endTime = '18:59:59';
            } elseif($time == 3){
                // 晚
                $beginTime = '19:00:00';
                $endTime = '23:59:59';
            }
            if($beginTime) {
                $signParams['begintime'] = $date . ' ' . $beginTime;
                $signParams['endtime'] = $date . ' ' . $endTime;
            }
   
        }
        $signList = $this->dataModel->get_student_sign_list($signParams);
        foreach($signList as $key => $sign) {
            // 获取学生头像
            $headimg = $this->staticWxUrl . 'assets/img/head.png';
            if(isset($studentList[$sign['student_id']])) {
                if($studentList[$sign['student_id']]['face_image']) {
                    $headimg = $studentList[$sign['student_id']]['face_image'] . '!small';
                }
            }
            $signList[$key]['headimg'] = $headimg;
            // 签到时间去掉秒
            $signList[$key]['createtime'] = time_remove_second($sign['createtime']);
            // 获取闸机描述
            $gateDesc = '校园闸机';
            if(isset($gateList[$sign['device_sn']]) && $gateList[$sign['device_sn']]['device_desc']) {
                $gateDesc = $gateList[$sign['device_sn']]['device_desc'];
            }
            // 出口还是入口
            if(isset($gateList[$sign['device_sn']]) && $gateList[$sign['device_sn']]['device_is_exit']  == 1) {
                $deviceIsExist = '（出口）';
            } else {
                $deviceIsExist = '（入口）';
            }
            $signList[$key]['gate_desc'] = $deviceIsExist . $gateDesc;
        }

        // 存筛选条件session
        $sessArr = array(
            "date" => $date,
			"class_id" => $classId,
			"keyword" => $this->get('keyword') ? $this->get('keyword') : ''
        );
        $this->session->set_userdata('gate_sign', $sessArr);
        // echo'<pre>';var_export($this->session);exit;
        exit(json('', true, $signList));
    }
}